I need to create a grayscale image in PHP. I am not talking about an indexed image with grayscale values in its palette, but about a TRUE grayscale image. The difference is in the 26th byte of the PNG (color type):
0 - greyscale <-- THIS IS WHAT I NEED
2 - RGB
3 - RGB with palette
4 - greyscale + alpha
6 - RGB + alpha
(See How to check a PNG for grayscale/alpha color type? for details)
I tried imagefilter($im, IMG_FILTER_GRAYSCALE);
as well as imagetruecolortopalette($im, false, 255);
but all I get are either RGB grayscale images (color type 2) or RGB palette images with a grayscale palette (color type 3). I also tried to initialize the image with imagecreate()
instead of imagecreatetruecolor()
but again this only leads to a palette image.
Is there any way to create a color type 0 grayscale PNG with PHP's GD functions (or any other functions in PHP)?
Here are some samples of different grayscale images to show what I mean. They all look the same, but if you open them in PhotoShop and look at the Image -> Mode setting, you see the difference. Also a hex editor will reveal the difference in the 26th byte:
RGB, color type 2, 3149 bytes
RGB palette, color type 3, 3971 bytes
True grayscale image, color type 0, 1105 bytes <-- THIS IS WHAT I NEED
UPDATE 01:
Here is the basic code that I use to create the PNGs. Commented lines are alternatives that I have tried:
//$im = imagecreate($image_size, $image_size);
$im = imagecreatetruecolor($image_size, $image_size);
//imagefilter($im, IMG_FILTER_GRAYSCALE);
//imagetruecolortopalette($im, false, 255);
imagepng($im, $imgPathName);
imagedestroy($im);