O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Special Effects Using imagefilter()

Warning

The filters described here were written for the PHP-bundled build of GD, and may not be available in other releases.

The best way to explain this function is to describe how it works, then show a code example. Although the function accepts different numbers of parameters that do very different things, the function returns true if the filter was applied successfully and false otherwise.

First up is IMG_FILTER_BRIGHTNESS, which takes a number between -255 and 255 that represents how much you want to brighten or darken the image. Setting it to 0 leaves the picture unchanged, 255 sets it to full white (brightest), and -255 sets it to full black (darkest). Most pictures tend to look almost invisible beyond +200 or -200.

This code example will lighten our space picture just a little:

    $image = imagecreatefrompng("space.png");
    imagefilter($image, IMG_FILTER_BRIGHTNESS, 50);
    header("content-type: image/png");
    imagepng($image);
    imagedestroy($image);

Next up is IMG_FILTER_COLORIZE, which takes three parameters between -255 and 255 that respectively represent the red, green, and blue values you want to add or subtract from the image. Setting the blue value to -255 will take all the blue out of all the pixels in the image, whereas setting the red to 128 will add red to them. Setting all three of them to 128 will have the effect of adding white to the picture, brightening it in the same way as IMG_FILTER_BRIGHTNESS.

This code example will make our image look ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required