How to Resize PNGs with Transparency in PHP without Losing Alpha
When attempting to resize PNG images with transparency in PHP, many users encounter issues with the background color changing to black. This article will address this problem and provide a solution.
The key lies in setting the image blending mode and alpha channel save flag appropriately before allocating transparency.
Here's the updated code:
function resizePNG($image, int $newWidth, int $newHeight) { // Create a new true color image $newImg = imagecreatetruecolor($newWidth, $newHeight); // Disable blending and enable alpha saving imagealphablending($newImg, false); imagesavealpha($newImg, true); // Allocate transparent color $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127); // Fill the new image with transparent color imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent); // Get the width and height of the original image $src_w = imagesx($image); $src_h = imagesy($image); // Copy and resize the original image onto the new image imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h); // Return the new resized image return $newImg; }
Using this updated code, PNG images with transparency can be resized without affecting the alpha channel, ensuring that the transparency is preserved.
The above is the detailed content of How to Resize PNGs with Transparency in PHP Without Losing Alpha?. For more information, please follow other related articles on the PHP Chinese website!