PHP GD only: PNG24+Alpha => PNG8 does not save Alpha

1k views Asked by At

Please do not post code which you have not actually tested! I have spent some time looking for this answer. There are several similar posts here on StackOverflow, but nothing I have found can produce this seemingly simple result.

pngquant is very nice for certain uses, but in this case, I have a specific use which I am trying to fill, which means using only the generic PHP with GD install.

Now the relevant code in its entirety! This simple code, produces a high color PNG image, with a translucent alpha channel. Works great, simple and effective!

<?php
$img = imagecreatetruecolor(50, 50);
imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 65, 65, 65, 20);
imagefill($img, 0, 0, $color);

header('content-type: image/png');
imagepng($img, 'test.png');
imagedestroy($img);

print file_get_contents('test.png');
?>

The following, nearly identical code, produces an 8bit PNG image file, unfortunately, the Alpha channel data is lost.

<?php
$img = imagecreatetruecolor(50, 50);
imagesavealpha($img, true);
$color = imagecolorallocatealpha($img, 65, 65, 65, 20);
imagefill($img, 0, 0, $color);
imagetruecolortopalette($img, false, 255); #this line missing in sample above
header('content-type: image/png');
imagepng($img, 'test.png');
imagedestroy($img);

print file_get_contents('test.png');
?>

Knowing that an 8bit PNG with alpha channel is demonstrably possible, can PHP GD do it, or not? It appears PHP GD is incapable, a bit of a turkey, but some of you are far more advanced than I am and may know the definitive answer one way or the other...

thanks in advance for any help.

1

There are 1 answers

4
Jost On

I think you should call imagesavealpha after you did the palette conversion, so the new/converted palette is "adapted" with alpha values. This should work:

<?php
$img = imagecreatetruecolor(50, 50);

$color = imagecolorallocatealpha($img, 65, 65, 65, 20);
imagefill($img, 0, 0, $color);
imagetruecolortopalette($img, false, 255);

imagesavealpha($img, true);

header('content-type: image/png');
imagepng($img, 'test.png');
imagedestroy($img);

print file_get_contents('test.png');
?>