The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case.
Even though imagesavealpha
is set, something isn't quite right.
What's the best way to preserve the transparency in the resampled image?
$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType )
= getimagesize( $uploadTempFile );
$srcImage = imagecreatefrompng( $uploadTempFile );
imagesavealpha( $targetImage, true );
$targetImage = imagecreatetruecolor( 128, 128 );
imagecopyresampled( $targetImage, $srcImage,
0, 0,
0, 0,
128, 128,
$uploadWidth, $uploadHeight );
imagepng( $targetImage, 'out.png', 9 );
Here is my total test code. It works for me
I believe this should do the trick:
edit: Someone in the PHP docs claims
imagealphablending
should be true, not false. YMMV.Pay attention to the source image's
width
andheight
values which are passed toimagecopyresampled
function. If they are bigger than actual source image size, the rest of image area will be filled with black color.An addition that might help some people:
It is possible to toggle imagealphablending while building the image. I the specific case that I needed this, I wanted to combine some semi-transparent PNG's on a transparent background.
First you set imagealphablending to false and fill the newly created true color image with a transparent color. If imagealphablending were true, nothing would happen because the transparent fill would merge with the black default background and result in black.
Then you toggle imagealphablending to true and add some PNG images to the canvas, leaving some of the background visible (ie. not filling up the entire image).
The result is an image with a transparent background and several combined PNG images.
I have made a function for resizing image like JPEG/GIF/PNG with
copyimageresample
and PNG images still keep there transparency:I combined the answers from ceejayoz and Cheekysoft, which gave the best result for me. Without imagealphablending() and imagesavealpha() the image is not clear: