Creating Transparent PNG Images in GD

March 27th, 2007

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:

    <?php
    // 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.