When using PHP's GD library to process images, many developers will encounter such confusion:
"I clearly set a transparent color with imagecolorallocatealpha() , why is the last PNG file saved completely opaque?"
Let's analyze this problem carefully and find the correct solution.
First, suppose you wrote a code like this:
<?php
$width = 200;
$height = 100;
// Create a true color image
$image = imagecreatetruecolor($width, $height);
// Assign a color with transparency
// Parameter order:R, G, B, Alpha(0 Totally opaque,127 Completely transparent)
$transparentColor = imagecolorallocatealpha($image, 255, 0, 0, 127);
// Fill the background with this color
imagefill($image, 0, 0, $transparentColor);
// Save as PNG
imagepng($image, 'output.png');
// Destroy resources
imagedestroy($image);
?>
You expect to generate a completely transparent PNG image on a red background, but after opening the file, you find that the background is red opaque.
Why?
The imagecolorallocatealpha() of the GD library is just assigned a color containing the alpha information, but this does not mean that when saving the PNG file, GD will automatically retain the alpha channel.
To make the transparency information properly saved to PNG, you need to explicitly enable two things:
Turn on alpha channel to save <br> Use imagesavealpha($image, true) to tell the GD library to include an alpha channel when saving PNG.
Turn off alpha mix (optional, but recommended)
Use imagealphableending($image, false) to make sure you don't mix colors incorrectly when manipulating image pixels.
<?php
$width = 200;
$height = 100;
// Create a true color image
$image = imagecreatetruecolor($width, $height);
// closure alpha mix(To properly save transparent background)
imagealphablending($image, false);
// Enable Save alpha Channel information
imagesavealpha($image, true);
// 分配一个Completely transparent的红色
$transparentColor = imagecolorallocatealpha($image, 255, 0, 0, 127);
// Fill the background with this color
imagefill($image, 0, 0, $transparentColor);
// Save as PNG
imagepng($image, 'output.png');
// Or save to the web page to output directly
// header('Content-Type: image/png');
// imagepng($image);
// Destroy resources
imagedestroy($image);
?>
This code generates a PNG image with a transparent red background.
If you set transparent color with imagecolorallocatealpha() in PHP, but the saved PNG is opaque, it is usually because you forgot:
? Use imagealphableending($image, false)
? Use imagesavealpha($image, true)
These two steps are key to transparent PNG preservation.
Related Tags:
PNG