Search code examples
phppngtransparencygdalpha

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 );

Solution

  • 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 );