Converting Images to Grayscale using PHP and the GD Library

 

http://php.about.com/od/gdlibrary/ss/grayscale_gd.htm

 

Before and After greyscale

 

 <?php 
 // The file you are grayscaling 
 $file = 'yourfile.jpg'; 

 // This sets it to a .jpg, but you can change this to png or gif if that is what you are working with
 header('Content-type: image/jpeg'); 

 // Get the dimensions
 list($width, $height) = getimagesize($file); 

 // Define our source image 
 $source = imagecreatefromjpeg($file); 

 // Creating the Canvas 
 $bwimage= imagecreate($width, $height); 

 //Creates the 256 color palette
 for ($c=0;$c<256;$c++) 
 {
 $palette[$c] = imagecolorallocate($bwimage,$c,$c,$c);
 }

 //Creates yiq function
 function yiq($r,$g,$b) 
 {
 return (($r*0.299)+($g*0.587)+($b*0.114));
 } 

The first thing we do with this code is define what file we are going to grayscale, and then (since our sample is a JPG) set the headers to be a JPG file. We then get the height and width from the image, define it as our source, and create a canvas of the correct size.

Next we need to create a color palette. We only need 256 colors (in shades from white to black) and the quickest way to define them is to use a loop to count up from 1 to 256.

Finally we create a function called yiq (). The YIG formulas used in our function come from those that use to be used in black and white televisions. This helps us get a better starting point for changing the colors to shades of gray.

 //Reads the origonal colors pixel by pixel 
 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;

 //This is where we actually use yiq to modify our rbg values, and then convert them to our grayscale palette
 $gs = yiq($r,$g,$b);
 imagesetpixel($bwimage,$x,$y,$palette[$gs]);
 }
 } 

 // Outputs a jpg image, but you can change this to png or gif if that is what you are working with
 imagejpeg($bwimage); 
 ?> 

The first thing you will see in this code is two loops, one related to the Y value, the other to the X value. These loop through to form the coordinates for each pixel in our photo.

We use the function imagecolorat () to get the index color of each pixel, and then apply ouryiq () filter. Finally we use imagesetpixel to reset the pixel to the appropriate value on our grayscale palette. Then the loop starts over and we do it to the next pixel, until all the pixels have been reassigned to a grey shade.

Finally we create our black and white image as a JPG.

Leave a Reply