If you need to convert an image to greyscale (or grayscale) using PHP then code is for you! It can handle Truecolor and indexed images and I have tested with JPG and PNG images.
Lots of examples out there assume your input image is truecolor. If you are trying to convert an indexed PNG these examples result in a completely black image.
The example below tests the input image and handles the colour conversion correctly. This code can easily be used to create a function that accepts an image resource and returns the greyscale version.
<?php
// Source image to open
$src_file = "test.jpg";
// Load image
$img_src = ImageCreateFromjpeg($src_file);
// Get dimensions of source image
$img_srcw = imagesx($img_src);
$img_srch = imagesy($img_src);
// Create a blank truecolor image with the same dimensions
$img_dst = imagecreatetruecolor($img_srcw,$img_srch);
// Loop through every pixel of source image
for ($i=0; $i<$img_srcw; $i++) {
for ($j=0; $j<$img_srch; $j++) {
// Get the colour of pixel
$colour = ImageColorAt($img_src, $i, $j);
// Get RGB values
if (imageistruecolor($img_src)) {
// Image is true colour so $colour
// contains RGB value
$rr = ($colour >> 16) & 0xFF;
$gg = ($colour >> 8) & 0xFF;
$bb = $colour & 0xFF;
} else {
// Image is not true colour so $colour
// contains index to a colour
$colour_tran = imagecolorsforindex($img_src, $colour);
$rr = $colour_tran['red'];
$gg = $colour_tran['green'];
$bb = $colour_tran['blue'];
}
// Calculate grey value
$g = round(($rr + $gg + $bb) / 3);
// Create that colour in the images palette
$colour_grey = imagecolorallocate($img_dst, $g, $g, $g);
// Set the pixel in output image to grey colour
imagesetpixel ($img_dst, $i, $j, $colour_grey);
}
}
// Generate and output JPG image
header("Content-type: image/jpeg");
imagejpg ($img_dst);
// Destroy images and free memory
imagedestroy($img_src);
imagedestroy($img_dst);
?>
$img_src = ImageCreateFromjpeg($src_file);
...
header("Content-type: image/jpeg");
imagejpg ($img_dst);