我尝试使用php合并两个图像。我做了之后,输出颜色与原点不一样。 我的代码怎么了?
图片1
图片2
输出
这是我的代码
$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 :(得分:1)
作为@Niet,Dark Absol说,你需要imagecreatetruecolor
而不是imagecreate
。但是,您需要更多步骤来保持透明度。主要功能包括imagesavealpha
和imagefill
。前者保留透明度,后者为新创建的图像提供透明背景。这是一份工作副本:
$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');
答案 1 :(得分:0)
使用imagecreate
创建的图像是基于调色板的,因此限制为256色。你有高度渐变的图像。请改用imagecreatetruecolor
。