Home >Backend Development >PHP Tutorial >How Can I Preserve Transparency When Resizing PNG Images with PHP\'s GDlib?

How Can I Preserve Transparency When Resizing PNG Images with PHP\'s GDlib?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 13:39:26953browse

How Can I Preserve Transparency When Resizing PNG Images with PHP's GDlib?

Preserving Transparency in PNG Images with GDlib's imagecopyresampled

When resizing PNG images with PHP's GDlib imagecopyresampled function, preserving transparency is crucial. One common issue is that the transparent areas become solid, typically black or another undesirable color.

Problem Statement

Consider the following PHP code snippet:

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

This code successfully resizes a browser-uploaded PNG image to 128x128. However, the transparent areas in the original image are replaced with black. Despite setting imagesavealpha to true, transparency is not being preserved.

Solution

The solution to preserve transparency is:

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

By setting imagealphablending to false and imagesavealpha to true, the transparency in the target image is maintained after the resizing operation.

Full Replacement Code

Including the transparency settings, the full replacement code is:

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

The above is the detailed content of How Can I Preserve Transparency When Resizing PNG Images with PHP\'s GDlib?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn