2009-09-08 58 views
20

情況是這樣的:我有一個小的50x50圖片。我也有一個小的50x50透明圖片,其中包含一個用於50x50圖片的框架,所以我基本上希望將透明png 放在圖片的頂部上,並將這兩個圖片合併,這會導致最終的第三張圖片看起來像這樣:http://img245.imageshack.us/i/50x50n.png如何使用PHP將透明PNG與圖像合併?

注:我不想這樣做只使用HTML(我通過編寫一個JavaScript插件,將透明PNG放在原始圖像的頂部)來實現此目的。

謝謝。

回答

29

您可以使用PHP GD2庫將兩個圖像合併在一起。

例子:

<?php 
# If you don't know the type of image you are using as your originals. 
$image = imagecreatefromstring(file_get_contents($your_original_image)); 
$frame = imagecreatefromstring(file_get_contents($your_frame_image)); 

# If you know your originals are of type PNG. 
$image = imagecreatefrompng($your_original_image); 
$frame = imagecreatefrompng($your_frame_image); 

imagecopymerge($image, $frame, 0, 0, 0, 0, 50, 50, 100); 

# Save the image to a file 
imagepng($image, '/path/to/save/image.png'); 

# Output straight to the browser. 
imagepng($image); 
?> 
+0

我試過這個,但我的透明框架剛剛在中間變成了白色。假設是什麼問題。 – 2012-02-08 09:06:14

+0

你可能想添加'header('Content-Type:image/png');'在最後一行之前確保將正確的MIME類型發送到瀏覽器 – 2012-05-16 06:04:55

+0

這對我來說也不起作用,它不會似乎保存了alpha通道。我也嘗試添加下面用戶提到的alpha混合標誌。 – Gazillion 2012-06-27 20:18:56

8

imagecopymerge()之前添加imagealphablending($frame,true);如果你想保留PNG框架transparancy在圖像上。

+3

圖像仍然透過白色的透明區域。 – AVProgrammer 2011-11-29 19:31:39

+1

我得到同樣的東西。有沒有解決這個問題呢? – Adam 2013-01-11 00:53:00