I'm trying to save image as a real grayscale image. I believe the way I'm doing in PHP using imagefilter($im, IMG_FILTER_GRAYSCALE)
or using the codes below are not saving the image as true grayscale but as RGB JPG of a grayscale image, as stated here.
function imagegreyscale(&$img, $dither=0) {
if (!($t = imagecolorstotal($img))) {
$t = 256;
imagetruecolortopalette($img, $dither, $t);
}
for ($c = 0; $c < $t; $c++) {
$col = imagecolorsforindex($img, $c);
$min = min($col['red'],$col['green'],$col['blue']);
$max = max($col['red'],$col['green'],$col['blue']);
$i = ($max+$min)/2;
imagecolorset($img, $c, $i, $i, $i);
}
}
function imagetograyscale($im)
{
if (imageistruecolor($im)) {
imagetruecolortopalette($im, false, 256);
}
for ($c = 0; $c < imagecolorstotal($im); $c++) {
$col = imagecolorsforindex($im, $c);
$gray = round(0.299 * $col['red'] + 0.587 * $col['green'] + 0.114 * $col['blue']);
imagecolorset($im, $c, $gray, $gray, $gray);
}
}
I compared the photo that my PHP code generated with the grayscale photo rendered by IrfanView. And the results are below. The first image shows a JPG without the word "Grayscale" while the second (by Irfanview) seems to be a real grayscale.
I need a true grayscale image to ensure my image is the smallest in file size without reducing dimension and quality further. So, how do I truly create a grayscale image using PHP?