1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Converting Images to Grayscale using PHP and the GD Library


1 of 2

Preparing the Canvas
Before and After greyscale

Photo of Alexa Bradley before and after we greyscale

Angela Bradley
 // 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.

  1. About.com
  2. Technology
  3. PHP / MySQL
  4. Graphics- GD Library
  5. Coverting Images to Grayscale Using PHP and GD Library

©2014 About.com. All rights reserved.