Home >Backend Development >PHP Tutorial >How Can I Preserve Transparency When Resizing PNGs with PHP GDlib?

How Can I Preserve Transparency When Resizing PNGs with PHP GDlib?

Susan Sarandon
Susan SarandonOriginal
2024-11-30 08:48:12295browse

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:

  1. Set the image alpha blending mode to false using imagealphablending($targetImage, false), where $targetImage is the resampled image.
  2. Set image alpha saving to true using imagesavealpha($targetImage, true).

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!

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