Home >Backend Development >PHP Tutorial >How Can I Preserve Transparency When Resizing PNGs with PHP GDlib?
Preserving Transparency in Resized PNGs with PHP GDlib
When resampling a PNG image using PHP's GDlib, it's common to encounter an issue where transparent areas in the original image are filled with a solid color. This occurs even when the imagesavealpha() function is used.
To ensure transparency is preserved in the resampled image, the following additional steps must be taken:
Example Code:
The following revised code demonstrates the corrected approach:
$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);
By incorporating these additional steps, the transparency in the resized PNG image will be maintained, enabling the preservation of transparent elements such as logos or background images.
The above is the detailed content of How Can I Preserve Transparency When Resizing PNGs with PHP GDlib?. For more information, please follow other related articles on the PHP Chinese website!