PHP / MySQL

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

Converting Images to Grayscale using PHP and the GD Library

By Angela Bradley, About.com

1 of 2

Preparing the Canvas

Before and After greyscale

Photo of Alexa Bradley before and after we greyscale

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

Explore PHP / MySQL

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

PHP / MySQL

  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.