2014-02-17 76 views
0

我在這裏只用了一點點的PHP GDLib。我試圖將兩個.PNG圖像疊加在彼此之上,迄今爲止工作正常。在保留透明度的同時複製下一張圖片,同時保留透明度

我遇到的一個問題是,有時,疊加圖像帶有白色背景。我可以使這個透明(使用imagecolortransparent函數),但是當我將這個圖像複製到一個新圖像時,這個透明度不會被保存。

// Load the background image first 

$background = imagecreatefrompng($this->background); 

// Load the overlaying image next, and set white as a transparent color 

$overlay = imagecreatefrompng($this->image); 
imagecolortransparent($overlay, imagecolorallocate($overlay, 255, 255, 255)); 

// So far, this all works. But when I create a new image, 
// and paste both $background and $overlay into it, 
// $overlay loses transparency and reverts to a white fill. 

$image = imagecreatetruecolor(16, 16); 
imagesavealpha($image, true); 
$trans_colour = imagecolorallocatealpha($image, 255, 255, 255, 127); 
imagefill($image, 0, 0, $trans_colour); 

imagecopyresampled($image, $background, 0, 0, 0, 0, 16, 16, 16, 16); 
imagecopyresampled($image, $overlay, 0, 0, 0, 0, 16, 16, 16, 16); 
@mkdir(dirname($file), 0777, true); 
imagepng($image, $file); 

// The new $image is now mostly white. The transparency on $overlay 
// was lost, meaning that the $background image is completely invisible. 

如何在將$overlay複製到新圖像時保持透明度?

+0

您的示例代碼中存在語法錯誤。用於'imagesavealpha()'的PHP文檔說:「您必須取消設置alphablending('imagealphablending($ im,false)')以使用它。」你也試過'imagecopyresized()'而不是'imagecopyresampled()'? – miken32

+0

@ miken32我已經做了更多的實驗。我已經修正了這個例子中的語法錯誤(只是複製粘貼錯誤,顯然它不在實際腳本中)。我還刪除了'imageSaveAlpha()',並將我的'imageCopyResampled()'變成了'imageCopyResized()'。最終的結果是現在的疊加層實際上是透明的,但最終的圖像不是。這現在有一個白色的背景。 – Duroth

+0

我想你還是需要在用imagepng()輸出之前調用'imageSaveAlpha()'。 – miken32

回答

0
$photo_to_paste = "photo_to_paste.png"; 
$white_image = "white_image.png"; 

$im = imagecreatefrompng($white_image); 
$im2 = imagecreatefrompng($photo_to_paste); 

imagecopy($im, $im2, (imagesx($im)/2) - (imagesx($im2)/2), (imagesy($im)/2) - (imagesy($im2)/2), 0, 0, imagesx($im2), imagesy($im2)); 

// Save alpha for the destination image. 
imagesavealpha($im, true); 
$trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127); 
imagefill($im, 0, 0, $trans_colour); 

// Save final image after placing one on another image 
imagepng($im, "output.png", 0); 

imagedestroy($im); 
imagedestroy($im2); 
相關問題