我必须垂直合并两个PNG图像。
//place at right side of $img1
imagecopy($merged_image, $img2, $img1_width, 0, 0, 0, $img2_width, $img2_height);
但我需要在底部之后合并图像。(垂直)
如何在第一张图像的底部合并第二张图像?
请指教!
PHP代码
$img1_path = 'images/1.png';
$img2_path = 'images/2.png';
list($img1_width, $img1_height) = getimagesize($img1_path);
list($img2_width, $img2_height) = getimagesize($img2_path);
$merged_width = $img1_width + $img2_width;
//get highest
$merged_height = $img1_height > $img2_height ? $img1_height : $img2_height;
$merged_image = imagecreatetruecolor($merged_width, $merged_height);
imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);
$img1 = imagecreatefrompng($img1_path);
$img2 = imagecreatefrompng($img2_path);
imagecopy($merged_image, $img1, 0, 0, 0, 0, $img1_width, $img1_height);
//place at right side of $img1
imagecopy($merged_image, $img2, $img1_width, 0, 0, 0, $img2_width, $img2_height);
//save file or output to broswer
$SAVE_AS_FILE = TRUE;
if( $SAVE_AS_FILE ){
$save_path = "images/Sample_Output.png";
imagepng($merged_image,$save_path);
}else{
header('Content-Type: image/png');
imagepng($merged_image);
}
//release memory
imagedestroy($merged_image);
输出:
答案 0 :(得分:1)
当我考虑功能
时imagecopy的(资源$ dst_im和,资源$和src_im,INT $ dst_x,INT $ dst_y,INT $从src_x,INT $ src_y,INT $ src_w,INT $ src_h)
它表示dst_x
和dst_y
应分别是目标点的x坐标和目标点的y坐标。
因此要垂直合并两个图像,它应该是这样的。
imagecopy($merged_image, $img2, 0,$img1_height , 0, 0, $img2_width, $img2_height);
您还应根据需要更改最终结果的$merged_width
和$merged_height
变量值。更改以下两行,
$merged_width = $img1_width + $img2_width; //get highest
$merged_height = $img1_height > $img2_height ? $img1_height : $img2_height;
如下,
$merged_width = $img1_width > $img2_width ? $img1_width : $img2_width; //get highest width as result image width
$merged_height = $img1_height + $img2_height;
最终结果:
$img1_path = 'images/1.png';
$img2_path = 'images/2.png';
list($img1_width, $img1_height) = getimagesize($img1_path);
list($img2_width, $img2_height) = getimagesize($img2_path);
$merged_width = $img1_width > $img2_width ? $img1_width : $img2_width; //get highest width as result image width
$merged_height = $img1_height + $img2_height;
$merged_image = imagecreatetruecolor($merged_width, $merged_height);
imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);
$img1 = imagecreatefrompng($img1_path);
$img2 = imagecreatefrompng($img2_path);
imagecopy($merged_image, $img1, 0, 0, 0, 0, $img1_width, $img1_height);
//place at right side of $img1
imagecopy($merged_image, $img2, 0,$img1_height , 0, 0, $img2_width, $img2_height);
//save file or output to broswer
$SAVE_AS_FILE = TRUE;
if( $SAVE_AS_FILE ){
$save_path = "images/Sample_Output.png";
imagepng($merged_image,$save_path);
}else{
header('Content-Type: image/png');
imagepng($merged_image);
}
//release memory
imagedestroy($merged_image);