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; } ?>
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!