如何删除图片中的透明颜色?

11

如何使用PHP最佳方法替换GIF和PNG图像中的透明颜色为白色?

// get transparent color indexes
$trsp = ImageColorsForIndex($image, ImageColorTransparent($image));
// get transparent color set
$delete = imagecolorallocate($image, $trsp['red'], $trsp['green'], $trsp['blue']); 
// replace
imagecolorset($image, $delete, 255, 255, 255);

无法工作。

1个回答

16

我并不经常使用GD库 - 我更喜欢ImageMagick。下面这种方法可以工作,但我不确定它是否最有效:

// Get the original image.
$src = imagecreatefrompng('trans.png');

// Get the width and height.
$width = imagesx($src);
$height = imagesy($src);

// Create a white background, the same size as the original.
$bg = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($bg, 255, 255, 255);
imagefill($bg, 0, 0, $white);

// Merge the two images.
imagecopyresampled(
    $bg, $src,
    0, 0, 0, 0,
    $width, $height,
    $width, $height);

// Save the finished image.
imagepng($bg, 'merged.png', 0);

我喜欢这个解决方案,因为它不会尝试替换半透明的颜色,该方法是加性重采样。 - Mike Kormendy
谢谢,迈克。新文件的文件大小比原始文件的大小大两倍半,这正常吗? - koredalin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接