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


