PNG24. The inversion of alpha channel (transparency)

GD and GD2 are useful libraries for creating graphics on-the-fly. Discuss your PHP GD and GD2 scripts here.

Moderators: onion2k, General Moderators

Post Reply
Kiosuki
Forum Newbie
Posts: 2
Joined: Thu Jun 19, 2008 1:49 am

PNG24. The inversion of alpha channel (transparency)

Post 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
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

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

Post 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.
Post Reply