达是酒中趣,琴上偶然音

PHP的图片处理功能

· Technology

在一个小项目里需要用到php的图像处理功能,才发现php通过imagefilter能够实现强大的功能。

imagefilter

(PHP 5)

imagefilter — Applies a filter to an image

Description

bool imagefilter ( resource $image , int $filtertype [, int $arg1 [, int $arg2 [, int $arg3[, int $arg4 ]]]] )

imagefilter() applies the given filter filtertype on the image.

Parameters

image An image resource, returned by one of the image creation functions, such as imagecreatetruecolor(). filtertype filtertype can be one of the following:

arg1

arg2

arg3

arg4

Return Values

Returns TRUE on success or FALSE on failure.

我用到的几个功能

imagefilter($dst_r, IMG_FILTER_BRIGHTNESS, -80);

The documentation misses the exact meaning and valid ranges of the arguments for ImageFilter(). According to the 5.2.0 sources the arguments are:
IMG_FILTER_BRIGHTNESS
-255 = min brightness, 0 = no change, +255 = max brightness

IMG_FILTER_CONTRAST
-100 = max contrast, 0 = no change, +100 = min contrast (note the direction!)

IMG_FILTER_COLORIZE
Adds (subtracts) specified RGB values to each pixel. The valid range for each color is -255…+255, not 0…255. The correct order is red, green, blue.
-255 = min, 0 = no change, +255 = max
This has not much to do with IMG_FILTER_GRAYSCALE.

IMG_FILTER_SMOOTH
Applies a 9-cell convolution matrix where center pixel has the weight arg1 and others weight of 1.0. The result is normalized by dividing the sum with arg1 + 8.0 (sum of the matrix).
any float is accepted, large value (in practice: 2048 or more) = no change

ImageFilter seem to return false if the argument(s) are out of range for the chosen filter.

You must add imagesavealpha($im, true); so the alpha channel will be saved on the new image.

$im = imagecreatefrompng('image.png');
imagealphablending($im, false);

imagesavealpha($im, true);

if($im && imagefilter($im, IMG_FILTER_COLORIZE, 0,0,255,0)) {
    imagepng($im, 'image-new.png');
    imagedestroy($im);
}