Patch: Avatar PNG Transparency (Bugs)

by beornlake, Wednesday, June 18, 2014, 20:56 (3571 days ago)

We have several users who want to use PNG avatars with transparency. The PNG handling methods in PHP default to using a black background, so alpha channels are lost when uploaded to our forum. We patched our installation's resize_image() function in functions.inc.php with the following to preserve alpha channels when PNGs are uploaded:

Between these two lines (Sourceforge link):

if(empty($error)) $new_image=imagecreatetruecolor($new_width,$new_height) or $error = true;
if(empty($error)) imagecopyresampled($new_image,$current_image,0,0,0,0,$new_width,$new_height,$image_info[0],$image_info[1]) or $error = true;

We splice in this block:

if(empty($error)) {
  imagesavealpha($new_image, true);
  $transparency_fill = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
  imagefill($new_image, 0, 0, $transparency_fill);
}

This fills the image with transparency before pixels are copied to the new canvas. This implementation appears to be working properly on our installation, but further testing is always prudent. ;-)

Avatar

Patch: Avatar PNG Transparency

by Auge ⌂, Friday, June 20, 2014, 10:50 (3569 days ago) @ beornlake

We have several users who want to use PNG avatars with transparency. ...

if(empty($error)) {
imagesavealpha($new_image, true);
$transparency_fill = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
imagefill($new_image, 0, 0, $transparency_fill);
}

This fills the image with transparency before pixels are copied to the new canvas. This implementation appears to be working properly on our installation, but further testing is always prudent. ;-)

I'm new to the image creation process. That said, let's analyse the code (a bit). The description for the function imagesavealpha says "You have to unset alphablending, to use it.". Maybe it's a good idea to do that explicitely to ensure the use of the original image data.

Tschö, Auge

--
Trenne niemals Müll, denn er hat nur eine Silbe!

Patch: Avatar PNG Transparency

by beornlake, Friday, June 20, 2014, 13:59 (3569 days ago) @ Auge

I'm new to the image creation process. That said, let's analyse the code (a bit). The description for the function imagesavealpha says "You have to unset alphablending, to use it.". Maybe it's a good idea to do that explicitely to ensure the use of the original image data.

Indeed, that's correct. I had left the imagealphablending() call out because it defaults to being off, but you're probably right that it's a good idea to explicitly turn it off anyway:

if(empty($error)) {
  imagealphablending($new_image, false);
  imagesavealpha($new_image, true);
  $transparency_fill = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
  imagefill($new_image, 0, 0, $transparency_fill);
}

RSS Feed of thread