2014-06-28 111 views
1

我嘗試使用php合併兩個圖像。在我做之後,輸出顏色與原點不一樣。 我的代碼有什麼問題?ImageCopy輸出顏色

圖像1

enter image description here

圖像2

enter image description here

輸出

enter image description here

這是我的代碼

$top_file = '1.png'; 
$bottom_file = '2.png'; 
$top = imagecreatefrompng($top_file); 
$bottom = imagecreatefrompng($bottom_file); 

// get current width/height 
list($top_width, $top_height) = getimagesize($top_file); 
list($bottom_width, $bottom_height) = getimagesize($bottom_file); 

// compute new width/height 
$new_width = ($top_width > $bottom_width) ? $top_width : $bottom_width; 
$new_height = $top_height + $bottom_height; 

// create new image and merge 
$new = imagecreate($new_width, $new_height); 
imagecopy($new, $top, 0, 0, 0, 0, $top_width, $top_height); 
imagecopy($new, $bottom, 0, $top_height+1, 0, 0, $bottom_width, $bottom_height); 

// save to file 
imagepng($new, 'merged_image.png'); 

回答

0

使用imagecreate創建的圖像是基於調色板的,因此僅限於256色。你有高度漸變的圖像。改爲使用imagecreatetruecolor

1

作爲@Niet the Dark Absol說,你需要imagecreatetruecolor而不是imagecreate。但是,您需要更多步驟來保持透明度。主要功能包括imagesavealphaimagefill。前者保留透明度,後者則在新創建的圖像上放置透明背景。這裏是一個工作副本:

$top_file = '1.png'; 
$bottom_file = '2.png'; 
$top = imagecreatefrompng($top_file); 
$bottom = imagecreatefrompng($bottom_file); 

// get current width/height 
list($top_width, $top_height) = getimagesize($top_file); 
list($bottom_width, $bottom_height) = getimagesize($bottom_file); 

// compute new width/height 
$new_width = ($top_width > $bottom_width) ? $top_width : $bottom_width; 
$new_height = $top_height + $bottom_height; 

// create new image and merge 
$new = imagecreatetruecolor($new_width, $new_height); 
imagesavealpha($new, true); 

$trans_colour = imagecolorallocatealpha($new, 0, 0, 0, 127); 
imagefill($new, 0, 0, $trans_colour); 

imagecopy($new, $top, 0, 0, 0, 0, $top_width, $top_height); 
imagecopy($new, $bottom, 0, $top_height+1, 0, 0, $bottom_width, $bottom_height); 

// save to file 
imagepng($new, 'merged_image.png');