Filtering Image Streams with the GD Library in PHP - Controlling brightness and contrast with the imagefilter() function
(Page 3 of 4 )
In the section that you just read, I explained how to use the imagefilter() function to apply some basic graphic filters to an existing image stream. However, the versatility exposed by this function allows you to implement many other popular filters as well.
Below I coded another pair of practical examples. They show how to use this helpful function to control the brightness and contrast of a specified image stream. In these examples I used the same sample image that you saw in the previous section.
Given that, here are the respective signatures for these code samples:
// example of 'imagefilter()' function - Changes the brightness
of the image
try{
if(!$image=imagecreatefromgif('clouds.gif')){
throw new Exception('Error creating image');
}
// apply filter to image
if(!imagefilter($image,IMG_FILTER_BRIGHTNESS,30)){
throw new Exception('Error applying filter to image');
}
// display image to the browser
header("Content-type: image/gif");
imagegif($image);
// free memory
imagedestroy($image);
}
catch(Exception $e){
echo $e->getMessage();
exit();
}

// example of 'imagefilter()' function - Changes the contrast of
the image
try{
if(!$image=imagecreatefromgif('clouds.gif')){
throw new Exception('Error creating image');
}
// apply filter to image
if(!imagefilter($image,IMG_FILTER_CONTRAST,30)){
throw new Exception('Error applying filter to image');
}
// display image to the browser
header("Content-type: image/gif");
imagegif($image);
// free memory
imagedestroy($image);
}
catch(Exception $e){
echo $e->getMessage();
exit();
}

Definitely, after studying the signature for the above examples, you'll have to admit that the "imagefilter()" function that comes with the GD library is extremely useful for controlling some aspects of a selected image stream, such as its brightness and contrast. In this case you can see that the function accepts the type of filter to be applied, along with its intensity, as an input argument.
So far, so good, right? I hope you see the great potential of the "imagefilter()" function. It will let you apply a bunch of popular graphic filters to a selected image stream, which can be a real time saver for those PHP applications that fetch multiple images from one or more database tables.
Nevertheless, if you're actually thinking that the capacity of this function is only limited to applying the set of filters that you saw in the previous examples, I'm afraid that you're wrong, since it has many others that can be really handy.
If you're interested in learning how to use the remaining filters that can be applied with the "imagefilter()" function, click the link below and read the next section. You won't be disappointed, trust me.
Next: More graphic filters with the imagefilter() function >>
More PHP Articles
More By Alejandro Gervasio