Search the blog

If you’ve done image processing the PHP and GD you may have noticed that when working with PNG files transparency is not retained.

By default GD uses alpha blending; this means that any transparent pixels in the PNG files will be blended with whatever colour is behind it. If there is no colour behind it (in the case of a PNG file with transparency) it will use the default (usually black). To retain PNG transparency you need to switch off alpha blending mode. However, GD won't save the alpha channel by default so a second function needs to be called. So call these functions after creating your image resource and before you do any image processing:

// Transparent
imagealphablending($image, false);
imagesavealpha($image, true);

// Not transparent
imagealphablending($image, true);
imagesavealpha($image, false);

These functions return true/false on success/failure.

Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.