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