I was able to maintain transparency by preserving pixels before imagetruecolortopalettewith
function check_transparent($im) {
$width = imagesx($im);
$height = imagesy($im);
$pixels = array();
for($i = 0; $i < $width; $i++) {
for($j = 0; $j < $height; $j++) {
$rgba = imagecolorat($im, $i, $j);
$index = imagecolorsforindex($im, $rgba);
if($index['alpha'] == 127) {
$pixels[] = array($i, $j);
}
}
}
return $pixels;
}
then replace with
function replacePixels($im,$pixels){
$color = imagecolorallocatealpha($im, 0, 0, 0, 127);
foreach($pixels as $pixel)
imagesetpixel($im, $pixel[0], $pixel[1], $color);
}
as
$tpixels = check_transparent($image);
imagetruecolortopalette($image, true, 255);
replacePixels($image, $tpixels);
source
share