0

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.

4

1 回答 1

1

我认为您应该imagesavealpha在进行调色板转换后调用,因此新/转换后的调色板“适应”了 alpha 值。这应该有效:

<?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');
?>
于 2013-08-24T17:33:53.480 回答