Share on Google+Share on Google+

PHP GD Grayscale

This example shows how to Grayscale an image in php gd.


$file = 'images.jpg';

header('Content-type: image/jpeg');

list($width, $height) = getimagesize($file);

$source = imagecreatefromjpeg($file);

$bwimage= imagecreate($width, $height);

for ($c=0;$c<256;$c++)


$palette[$c] = imagecolorallocate($bwimage,$c,$c,$c);


function yiq($r,$g,$b)


return (($r*0.299)+($g*0.587)+($b*0.114));


for ($y=0;$y<$height;$y++)


for ($x=0;$x<$width;$x++)


$rgb = imagecolorat($source,$x,$y);

$r = ($rgb >> 16) & 0xFF;

$g = ($rgb >> 8) & 0xFF;

$b = $rgb & 0xFF;


$gs = yiq($r,$g,$b);






After running the program you will get the following output



Posted on: November 9, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.