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

How Can I Preserve Transparency When Resizing PNGs in PHP?

Susan Sarandon
Release: 2024-11-23 22:46:10
Original
190 people have browsed it

How Can I Preserve Transparency When Resizing PNGs in PHP?

Preserving Transparency When Resizing PNGs in PHP

When resizing PNG images with transparent backgrounds in PHP, it is crucial to ensure that the transparency is maintained. However, many online code samples fail to achieve this properly, resulting in a black background after resizing.

To address this issue, it is necessary to make specific adjustments to the code. Before performing the imagecolorallocatealpha() function, it is essential to configure both the blending mode and the save alpha channel flag to false and true, respectively.

Here's an updated code snippet that incorporates these adjustments:

<?php
/**
 * https://stackoverflow.com/a/279310/470749
 * 
 * @param resource $image
 * @param int $newWidth
 * @param int $newHeight
 * @return resource
 */
public function getImageResized($image, int $newWidth, int $newHeight) {
    $newImg = imagecreatetruecolor($newWidth, $newHeight);
    imagealphablending($newImg, false); // Turn off blending
    imagesavealpha($newImg, true); // Turn on save alpha channel
    $transparent = imagecolorallocatealpha($newImg, 255, 255, 255, 127);
    imagefilledrectangle($newImg, 0, 0, $newWidth, $newHeight, $transparent);
    $src_w = imagesx($image);
    $src_h = imagesy($image);
    imagecopyresampled($newImg, $image, 0, 0, 0, 0, $newWidth, $newHeight, $src_w, $src_h);
    return $newImg;
}
?>
Copy after login

With these modifications, the code should effectively maintain the transparency of PNG images after resizing.

Note: This updated code works correctly only for images with a background opacity of 0. If the image's opacity falls between 0 and 100, the background will appear black after resizing.

The above is the detailed content of How Can I Preserve Transparency When Resizing PNGs 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