In addition to code_couturier too: his code will produce blue pictures, because the value he uses to set the pixel color (the code is incomplete: I first thought it should be $gray) is between 0 and 255, which corresponds to blue levels.
To convert the picture to grayscale, use the following code:
<?php
$originalFileName = "colorPicture.jpg";
$destinationFileName = "bwPicture.jpg";
$fullPath = explode(".",$originalFileName);
$lastIndex = sizeof($fullPath) - 1;
$extension = $fullPath[$lastIndex];
if (preg_match("/jpg|jpeg|JPG|JPEG/", $extension)){
$sourceImage = imagecreatefromjpeg($originalFileName);
}
$img_width = imageSX($sourceImage);
$img_height = imageSY($sourceImage);
for ($y = 0; $y <$img_height; $y++) {
for ($x = 0; $x <$img_width; $x++) {
$rgb = imagecolorat($sourceImage, $x, $y);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
$gray = round(.299*$red + .587*$green + .114*$blue);
$grayR = $gray << 16; $grayG = $gray << 8; $grayB = $gray; $grayColor = $grayR | $grayG | $grayB;
imagesetpixel ($sourceImage, $x, $y, $grayColor);
imagecolorallocate ($sourceImage, $gray, $gray, $gray);
}
}
$destinationImage = ImageCreateTrueColor($img_width, $img_height);
imagecopy($destinationImage, $sourceImage, 0, 0, 0, 0, $img_width, $img_height);
imagejpeg($destinationImage, $destinationFileName);
imagedestroy($destinationImage);
imagedestroy($sourceImage);
?>
Copy-paste, replace the file names on the top and there you go (picture files must be in same folder as this script. If not, you will have to do your own file management).