public function convertToPaletteImage()
{
if (!imageistruecolor($this->gdResource)) {
return $this;
}
$width = imagesx($this->gdResource);
$height = imagesy($this->gdResource);
$transparentColor = null;
if ($this->countColors(256) <= 256) {
$paletteImage = imagecreate($width, $height);
$colors = array();
$isTransparent = false;
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
$color = imagecolorat($this->gdResource, $x, $y);
// Check if the pixel is fully transparent
if (($color >> 24 & 0x7f) === 127) {
$isTransparent = true;
} else {
$colors[$color & 0xffffff] = true;
}
}
}
$colors = array_keys($colors);
foreach ($colors as $index => $color) {
imagecolorset($paletteImage, $index, $color >> 16 & 0xff, $color >> 8 & 0xff, $color & 0xff);
}
if ($isTransparent) {
$transparentColor = imagecolorallocate($paletteImage, 0, 0, 0);
imagecolortransparent($paletteImage, $transparentColor);
}
imagecopy($paletteImage, $this->gdResource, 0, 0, 0, 0, $width, $height);
} else {
$paletteImage = imagecreatetruecolor($width, $height);
imagealphablending($paletteImage, false);
imagesavealpha($paletteImage, true);
imagecopy($paletteImage, $this->gdResource, 0, 0, 0, 0, $width, $height);
// 256 minus 1 for the transparent color
imagetruecolortopalette($paletteImage, false, 255);
$transparentColor = imagecolorallocate($paletteImage, 0, 0, 0);
imagecolortransparent($paletteImage, $transparentColor);
}
if ($transparentColor !== null) {
// Fix fully transparent pixels
for ($x = 0; $x < $width; $x++) {
for ($y = 0; $y < $height; $y++) {
// Check if the pixel is fully transparent
if ((imagecolorat($this->gdResource, $x, $y) >> 24 & 0x7f) === 127) {
imagefilledrectangle($paletteImage, $x, $y, $x, $y, $transparentColor);
}
}
}
}
imagedestroy($this->gdResource);
$this->gdResource = $paletteImage;
return $this;
}