Create a true shade of gray in PHP

I need to create a grayscale image in PHP. I'm not talking about a grayscale indexed image in my palette, but TRUE grayscale. The difference is in the 26th byte 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 PNG for grayscale / alpha? for more details)

I tried imagefilter($im, IMG_FILTER_GRAYSCALE);as well imagetruecolortopalette($im, false, 255);, but all I get is either grayscale (RGB) images (color 2) or RGB palette images with a gray palette (color 3). I also tried to initialize the image with imagecreate()instead imagecreatetruecolor(), but again this will only result in the image palette.

Is there a way to create a color format 0 in grayscale with PNG with PHP GD functions (or any other functions in PHP)?

Here are a few examples of different shades of gray 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 will see the difference. Also, the hex editor will detect the difference in the 26th byte:

RGBRGB, color type 2 , 3149 bytes
RGB paletteRGB palette, color 3 , 3971 bytes
True Grayscale ImageTrue grayscale image, color type 0 , 1105 bytes <- THIS IS NEEDED


UPDATE 01:

Here is the base code that I use to create PNG. Commented lines are alternatives I 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);
+5
source share
1 answer

GD "" . RGB TrueColor *.

0 PNG PHP GD ( PHP)?

ImageMagick - , .

$im = new Imagick();
$im->readImage('file.png');
$im->setImageType(Imagick::IMGTYPE_GRAYSCALE);
$im->writeImage('file.gray.png');
+5

All Articles