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

How to Preserve Transparency When Resizing PNGs in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-28 14:20:16623browse

How to Preserve Transparency When Resizing PNGs in PHP?

How to Resize PNGs with Transparent Backgrounds Effectively in PHP

Resizing transparent PNG images in PHP can be a challenging task, but it's essential for maintaining image quality. The code you've provided encounters an issue where the background color transforms to black upon resizing. To fix this, follow the updated code below:

$this->image = imagecreatefrompng($filename);

imagealphablending($this->image, false);
imagesavealpha($this->image, true);

$newImage = imagecreatetruecolor($width, $height);

// Allocate a new transparent color and enable alpha blending
$background = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($newImage, 0, 0, $width, $height, $background);
imagealphablending($newImage, true);
imagesavealpha($newImage, true);

// Resize the image with transparent background preserved
imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $newImage;

imagepng($this->image, $filename);

Key changes:

  • imagealphablending(false): Disables alpha blending before allocating the transparent color to prevent unwanted blending.
  • imagesavealpha(true): Enables transparent background saving before the image copy.
  • imagefilledrectangle(): Fills the new image with the transparent color.

Update:

The provided code handles transparent backgrounds with opacity set to 0. However, for images with opacity values between 0 and 100, it will still produce a black background. Unfortunately, there is no straightforward solution within the GD library to handle this use case.

The above is the detailed content of How to Preserve Transparency When Resizing PNGs in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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