用背景色填充 png 透明度



我正在重构大约 5 年前编写的旧图像裁剪/调整大小库,但我被困在尝试恢复它的功能之一时。有趣的是,我什至不确定它当时是否有效,因为我可能从未真正使用它。

我需要能够在保持透明度(有效(的同时处理 png 图像,但我也不想用颜色填充图像的透明部分。

创建一个空白图像并用颜色填充它工作得很好,但是当我尝试将 png 粘贴到它上面时,背景再次透明。

这是我代码的简化版本:

<?php
$src = imagecreatefrompng($pathToSomePngFile);
imagealphablending($src, false);
imagesavealpha($src, true);
$output = imagecreatetruecolor($width, $height);
if ($backgroundColor) {
$fillColor = imagecolorallocate(
$output, 
$backgroundColor['r'], 
$backgroundColor['g'], 
$backgroundColor['b']
);
imagefilledrectangle(
$output, 
0, 
0, 
$width, 
$height, 
$fillColor
);
} else {
imagealphablending($output, false);
imagesavealpha($output, true);
}
imagecopyresampled(
$output,
$src,
0,
0,
0,
0,
$width,
$height,
$width,
$height
);
imagepng($output, $pathToWhereImageIsSaved);

更新

使用 delboy1978uk 的解决方案进行了更新,使其无需更改我的其他设置即可工作。

这样的事情应该有效。

<?php
// open original image
$img = imagecreatefrompng($originalTransparentImage);
$width  = imagesx($img);
$height = imagesy($img);
// make a plain background with the dimensions
$background = imagecreatetruecolor($width, $height);
$color = imagecolorallocate($background, 127, 127, 127); // grey background
imagefill($background, 0, 0, $color);
// place image on top of background
imagecopy($background, $img, 0, 0, 0, 0, $width, $height);
//save as png
imagepng($background, '/path/to/new.png', 0);

最新更新