How to Properly Resize PNGs with Transparency in PHP?

Susan Sarandon
Release: 2024-11-25 05:03:15
Original
337 people have browsed it

How to Properly Resize PNGs with Transparency in PHP?

Resizing PNGs with Transparency in PHP: A Comprehensive Solution

In PHP, resizing PNG images with transparent backgrounds can be a challenge. To address this, one code sample that has proven ineffective requires a few crucial modifications to achieve the desired result. Here's a detailed explanation of what needs to be adjusted:

The code provided:

$this->image = imagecreatefrompng($filename);

imagesavealpha($this->image, true);
$newImage = imagecreatetruecolor($width, $height);

// Make a new transparent image and turn off alpha blending to keep the alpha channel
$background = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagecolortransparent($newImage, $background);
imagealphablending($newImage, false);
imagesavealpha($newImage, true);

imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height,  $this->getWidth(), $this->getHeight());
$this->image = $newImage;  
imagepng($this->image,$filename);
Copy after login

After carefully reviewing this code, it became evident that the issue lies in the statement where imagecolorallocatealpha() is called. The correct order of operations is vital here: you must first set the blending mode to false and the save alpha channel flag to true before executing imagecolorallocatealpha().

imagesavealpha($newImg, true);
imagealphablending($newImg, false);
Copy after login

After making this modification, your code should be able to successfully resize PNG images with transparent backgrounds, preventing the background from turning black.

Update for Images with Opacity between 0 and 100:

The provided code only works for images with opacity set to 0. If your image has an opacity between 0 and 100, the background will appear black. To resolve this issue, you will need to adjust the imagecopyresampled() function to use imagecopyresampled() instead, as it better handles transparent PNG images with varying opacity levels.

$transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent);
imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h);
Copy after login

The above is the detailed content of How to Properly Resize PNGs with Transparency in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template