2010-07-28 74 views
5

我有兩個PNG文件,「red.png」和「blue.png」;它們都是透明的,但在不同的地方有幾個像素的紅色或藍色斑點。PHP + GD:imagecopymerge不保留PNG透明膠片

我想做一個PHP腳本來合併這兩個;它應該像這樣簡單:

$original = getPNG('red.png'); 
$overlay = getPNG('blue.png'); 

imagecopymerge($original, $overlay, 0,0, 0,0, imagesx($original), imagesy($original), 100); 
header('Content-Type: image/png'); 
imagepng($original); 

當我運行這個腳本時,我得到的只是藍色的點 - 透明度丟失了。我看到我應該添加下列內容:

imagealphablending($original, false); 
imagesavealpha($original, true); 

(在原始和覆蓋?上)這似乎沒有任何幫助。

我看見有幾個解決方法上PHP.net,東西的調子:

$throwAway = imagecreatefrompng($filename); 
imagealphablending($throwAway, false); 
imagesavealpha($throwAway, true); 
$dstImage = imagecreatetruecolor(imagesx($throwAway), imagesy($throwAway)); 
imagecopyresampled($dstImage, $throwAway,0,0,0,0, imagesx($throwAway),  imagesy($throwAway),   imagesx($throwAway), imagesy($throwAway)); 

,這應該PNG轉換爲「真彩色」圖像並保留透明度。它似乎這樣做,但現在我看到的只是黑色背景上的藍色。

我該怎麼辦?

回答

6

這完美的作品對我來說:

$img1 = imagecreatefrompng('red.png'); 
$img2 = imagecreatefrompng('blue.png'); 

$x1 = imagesx($img1); 
$y1 = imagesy($img1); 
$x2 = imagesx($img2); 
$y2 = imagesy($img2); 

imagecopyresampled(
    $img1, $img2, 
    0, 0, 0, 0, 
    $x1, $y1, 
    $x2, $y2); 

imagepng($img1, 'merged.png', 0); 

PHP版本5.3.2
GD 2.0版
的libpng版本1.2.42

您是否嘗試過將圖像保存到一個文件,並檢查?

+0

完全合作。非常感謝!我仍然必須使用imagealphablending和imagesavealpha。 – 2010-07-28 19:38:29