Thursday, March 3, 2011

PNG Transparency with PHP

Hey having some trouble trying to maintain transparency on a png when i create a thumbnail from it, anyone any experience with this? any help would be great, here's what i am currently doing:

$fileName= "../js/ajaxupload/tees/".$fileName;

list($width, $height) = getimagesize($fileName);

$newwidth = 257;
$newheight = 197;

$thumb = imagecreatetruecolor($newwidth, $newheight);
imagealphablending($thumb, true);
$source = imagecreatefrompng($fileName);
imagealphablending($source, true);

imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

imagesavealpha($thumb, true);
imagepng($thumb,$newFilename);
From stackoverflow
  • See dycey's answer to "How do I resize...". Essentially, you need to fill the entire background with transparency before you do any other operations.

    strager : That question is still unanswered. Though, maybe the two need to be merged.
  • imagecopyresized does not support transparency properly.

    imagecopymerge does, but it doesn't resize.

    The solution? You'd probably end up resizing the thing manually.

  • I have had success doing it like this in the past:

    $thumb = imagecreatetruecolor($newwidth, $newheight);
    imagealphablending($thumb, false);
    imagesavealpha($thumb, true);  
    
    $source = imagecreatefrompng($fileName);
    imagealphablending($source, true);
    
    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
    
    imagepng($thumb,$newFilename);
    

    I found the output image quality much better using imagecopyresampled() than imagecopyresized()

    BastardPrince : that cracked it! much obliged!
  • Those functions access the underlying gdlib library, which is a fine toy, but not something that makes for nice results. If you have the option, use imagemagick instead. The downside is that there are currently no good php-bindings, so you need to access it over the shell, which you're usually not allowed on shared hosts.

0 comments:

Post a Comment