Page 1 of 1

PNG24. The inversion of alpha channel (transparency)

Posted: Thu Jun 19, 2008 3:22 am
by Kiosuki
I'm new here. I'm sorry beforehand wether this topic is similar some existing.
Now I explain the consern. There is PNG24 file with stuff imagination. The transparency is around it. How can I invert the alpha channel via PHP? As a result, transparent areas would be non-transparent and vice versa. That is, pixel with alpha 127 index should receive index 0, but, for example, with an index of 117 - get 10. How can I do? Thank you.

Roughly speaking it is necessary to obtain such a result: Image

Re: PNG24. The inversion of alpha channel (transparency)

Posted: Thu Jun 19, 2008 4:04 am
by onion2k
Loop through all the pixels in the image using imagecolorat() to get the color, then extract the alpha channel info, and use it to write a pixel to a new image.

Something like...

Code: Select all

$source = imagecreatefrompng("image.png");
 
$dest = imagecreatetruecolor(imagesx($source),imagesy($source));
imagealphablending($dest,false);
imagesavealpha($dest,true);
$trans = imagecolorallocatealpha($dest,0,0,0,127);
for ($y=0;$y<imagesy($dest);$y++) {
  for ($x=0;$x<imagesx($dest);$x++) {
    imagesetpixel($dest,$x,$y,$trans);
  }
}
 
for ($y=0;$y<imagesy($source);$y++) {
  for ($x=0;$x<imagesx($source);$x++) {
    $rgb = imagecolorat($source,$x,$y);
    $a = ($rgb >> 24) & 0xFF;
    $colour = imagecolorallocatealpha($dest,0,0,0,$a);
    imagesetpixel($dest,$x,$y,$colour);
  }
}
I haven't tested that, and if I was writing it properly I'd create a transparent destination image a bit differently.