How to Resize PNGs with Transparency in PHP Without Losing Alpha?

Susan Sarandon
Release: 2024-11-18 02:07:01
Original
311 people have browsed it

How to Resize PNGs with Transparency in PHP Without Losing Alpha?

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;
}
Copy after login

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!

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