如何删除图像中的透明色?

时间:2010-08-21 15:52:56

标签: php image gd

使用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 个答案:

答案 0 :(得分:14)

我并没有真正使用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);