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 );
I suppose that this might do the trick:
The downside is that the image will be stripped of every 100% green pixels. Anyhow, hope it helps :)
did it for me. Thanks ceejayoz.
note, the target image needs the alpha settings, not the source image.
Edit: full replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, but did achieve my needs at the time.
Why do you make things so complicated? the following is what I use and so far it has done the job for me.
Regrading the preserve transparency, then yes like stated in other posts imagesavealpha() have to be set to true, to use the alpha flag imagealphablending() must be set to false else it doesn't work.
Also I spotted two minor things in your code:
getimagesize()
to get the width/height forimagecopyresmapled()
$uploadWidth
and$uploadHeight
should be-1
the value, since the cordinates starts at0
and not1
, so it would copy them into an empty pixel. Replacing it with:imagesx($targetImage) - 1
andimagesy($targetImage) - 1
, relativily should do :)