Tuesday 14 August 2018

Image Manipulation with PHP and the GD Library

Yeah, I'm a Photoshop wizard. I rock the selection tool. I crop like a farmer. I dominate the bucket tool. Hell, I even went as far as wielding the wizard wand selection tool once.


...OK I'm rubbish when it comes to Photoshop. I avoid opening the memory pig whenever possible. Many times I even need to automate image manipulation on customer websites. Luckily for a nerd like me, PHP's GD library allows me to systematically execute basic image manipulations without the need for Photoshop, GIMP, or other desktop tools.

The PHP -- Color to Greyscale
//to black and white
if(!file_exists('dw-bw.png')) {
$img = imagecreatefrompng('dw-manipulate-me.png');
imagefilter($img,IMG_FILTER_GRAYSCALE);
imagepng($img,'db-bw.png');
imagedestroy($img);
}
The PHP -- Color to Negative
//to negative
if(!file_exists('dw-negative.png')) {
$img = imagecreatefrompng('dw-manipulate-me.png');
imagefilter($img,IMG_FILTER_NEGATE);
imagepng($img,'db-negative.png');
imagedestroy($img);
}
The PHP -- Color to Sepia
//to black and white, then sepia
if(!file_exists('dw-sepia.png')) {
$img = imagecreatefrompng('dw-manipulate-me.png');
imagefilter($img,IMG_FILTER_GRAYSCALE);
imagefilter($img,IMG_FILTER_COLORIZE,100,50,0);
imagepng($img,'db-sepia.png');
imagedestroy($img);
}
As you can see, PHP's GD library is a very competent, useful library. Though image libraries like ImageMagick get more credit than GD, GD is more than enough for the majority of designers and developers. Be sure to check out PHP image filters -- you can emboss images, fade images, and much more!

0 comments:

Post a Comment