首页 > 解决方案 > PHP - 使用 imagecopy 函数垂直合并两个图像

问题描述

我必须垂直合并两个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);

输出:

在此处输入图像描述

标签: phpimage-processingmerge

解决方案


当我考虑功能时

imagecopy ( 资源 $dst_im , 资源$src_im , int $dst_x , int $dst_y , int $src_x , int$src_y , int $src_w , int $src_h )

它表示dst_xdst_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);

推荐阅读