B2

Watching the distance between
posts increase exponentially.


Creating Transparent PNG Images in GD

For a project at work I had to create a true colour PNG from scratch using GD, copy a load of image files to it from various locations and then display it on-screen. The code to create a transparent PNG turned out to be a litle complicated:

 // create a true colour, transparent image
// turn blending OFF and draw a background rectangle in our transparent colour
$image=imagecreatetruecolor($iwidth,$iheight);
imagealphablending($image,false);
$col=imagecolorallocatealpha($image,255,255,255,127);

imagefilledrectangle($image,0,0,$iwidth,$iheight,$col);
imagealphablending($image,true);
// ^^ Alpha blanding is back on.

// insert image manipulation stuff in here

// output the results...
header("Content-Type: image/png;");
imagealphablending($image,false);
imagesavealpha($image,true);
imagepng($image);
?> 

Important Note: If you output the image direct into the document stream as this example does, the PNG fix that uses bahaviours won’t work as it’s not a true PNG. For that, you’ll have to drop the header and give imagepng() a filename and show that file. Seems to work fine in other browsers, however.

Originally Posted: 27th March 2007

Link to this page: HTML   BBCode
Copy the code from the box below into your website or message boardpost.


Reader Comments:

The following comments were left by other visitors and do not necessarily reflect the opinion of the author...
Thank you for the useful snippet. Creating transparent PNGs is bit magicful in PHP %)
Denis (?) | 05:50.51 18th Jun 2009
I was working on importing another transparent png and you got your code right on!

$srcimage=imagecreatefrompng($src);
imagecopyresampled($image,$srcimage,0,0,0,0,$iwidth,$iheight,$iwidth,$iheight);
Patrick McGuire (?) | 14:58.43 26th Aug 2009
Champion - works a treat.
Jimmy (?) | 09:47.18 8th Nov 2009
Very usefull, thanks!
Tivins (?) | 22:49.01 25th Jul 2010
Thanks! Saved my time :-)
Kiran (?) | 13:23.39 6th Jan 2011
Really appreciated piece of code!
Jean-Damien (?) | 18:00.02 16th Jan 2011
thanks for your code
it helps
vivian (?) | 09:04.03 1st Feb 2011