1. Home
  2. Computing & Technology
  3. PHP / MySQL

Converting Images to Grayscale using PHP and the GD Library

By , About.com Guide

2 of 2

Creating the B&W Image

Before and After greyscale

Photo of Alexa Bradley before and after we greyscale

Angela Bradley
//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 our yiq () 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.

Explore PHP / MySQL
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Graphics- GD Library
  5. Grayscale PHP GD Library - Greyscale PHP GD Library - Black and White GD Library

©2009 About.com, a part of The New York Times Company.

All rights reserved.