2010-08-21 80 views
7

用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); 

不起作用。

+0

好,雖然,質疑 – Latze 2010-08-21 18:06:51

回答

12

我並沒有真正使用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); 
+0

我喜歡這個解決方案,因爲它並不試圖替換顏色,如果他們是半透明的,在方法被重新採樣。 – 2014-10-08 07:17:52