Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can PNG image transparency be preserved when using PHP's GDlib imagecopyresampled?

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 ); 
like image 312
Cheekysoft Avatar asked Aug 28 '08 13:08

Cheekysoft


People also ask

Does PNG preserve transparency?

Transparency. The GIF and PNG formats also both support transparency. If you need any level of transparency in your image, you must use either a GIF or a PNG. GIF images (and also PNG) support 1-color transparency.

How does PNG images show transparency?

With any software that supports transparency in PNG images, the background onto which you've placed the image will show through the masked out (transparent) areas, so that the isolated subject in the photo will be set against that background.

Is PNG see through background?

If you are using a screenshot or a PNG image, it will default to have a transparent background. If you are using a JPG or other file format, you'll need to adjust your background color in the Snagit editor first or it will default to white rather than transparent.


1 Answers

imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); 

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.

$uploadTempFile = $myField[ 'tmp_name' ] list( $uploadWidth, $uploadHeight, $uploadType )    = getimagesize( $uploadTempFile );  $srcImage = imagecreatefrompng( $uploadTempFile );   $targetImage = imagecreatetruecolor( 128, 128 );    imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true );  imagecopyresampled( $targetImage, $srcImage,                      0, 0,                      0, 0,                      128, 128,                      $uploadWidth, $uploadHeight );  imagepng(  $targetImage, 'out.png', 9 ); 
like image 126
Cheekysoft Avatar answered Sep 28 '22 10:09

Cheekysoft