PHP + GD: imagetruecolortopalette does not preserve transparency

I use GD to output an image, which is a PNG file with truecolor + alpha channel, using imagepng is just fine. However, I would like to be able to also output 256-color PNG, compatible with ie6. According to official documentation for imagetruecolortopalette:

The code has been modified to save as much information about alpha channels in the resulting palette, in addition to preserving colors, as well as possible.

However, I find that the results of this function do not fully maintain transparency. I used this firefox image with text overlaid on top of it as a test, and the whole function was given to me on a white background and an oddly dark blue frame. I know that I cannot hope to keep the full alpha channel, but no doubt this feature will at least take away the transparent background. Is there something I'm missing? Are there any alternative approaches that I can take?

+3
source share
3 answers

I recently came across something like this: I could only get transparency with:

imagesavealpha($im, true);
imagecolortransparent($im, imagecolorat($im,0,0));

, . imagetruecolortopalette imagepng.

+3

imagesavealpha php- - , , .

0

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);
0
source

Source: https://habr.com/ru/post/1740766/


All Articles