PHP imagepng transparant turns black
October 24, 2009
I’m writing a web application that allows it’s users (among other things) to upload their company logos. PHP script is used to take the user provided jpgs/pngs and present them uniformly in a webpage. I ran into the problem that rescaled png images had their transparent regions turned black.
Here’s the solution I found;
- First create a new image (imagecreatetruecolor) with the required dimensions.
- Allocate a transparent color for that image. (imagecolorallocatealpha)
- Fill the image with the transparent color. (imagefilledrectangle)
- Now copy a scaled version of your original png image into the new image. (imagecopyresampled)
Voila.
Although the last step effectively overwrites all the pixels in your image, step 2 and 3 seem to be absolutely necessary to allow transparency inside your png image.
One more word of advice; use imagecopyresampled instead of imagecopyresized.
Resampled

Resampled "Dutch Design Award"
Resized

Resized "Dutch Design Award"
Advertisement

