在php中合并两个图像

joh*_*lly 4 php gd image image-processing

我有两个想要合并的图像然后保存到新位置.
我希望第二张图像直接放在第一张图像的下方.
我有以下所以,但图像甚至没有保存.

$destimg = imagecreatefromjpeg('images/myimg.jpg');

$src = imagecreatefromgif('images/second.gif');  

// Copy and merge
imagecopymerge($destimg, $src, 316, 100, 0, 0, 316, 100, 100);
Run Code Online (Sandbox Code Playgroud)

两个图像都有宽度或316px X 100px
从上面的代码中,$ destimg现在应该是316x200,但这不会发生.也喜欢它是一个新的图像并保存到另一个文件夹.

谢谢你的帮助.

Chr*_*son 16

针对这种情况的最佳方法可能是在内存中使用所需的组合尺寸创建新图像,然后将现有图像复制或重新采样到新图像,然后将新图像保存到磁盘.

例如:

function merge($filename_x, $filename_y, $filename_result) {

 // Get dimensions for specified images

 list($width_x, $height_x) = getimagesize($filename_x);
 list($width_y, $height_y) = getimagesize($filename_y);

 // Create new image with desired dimensions

 $image = imagecreatetruecolor($width_x + $width_y, $height_x);

 // Load images and then copy to destination image

 $image_x = imagecreatefromjpeg($filename_x);
 $image_y = imagecreatefromgif($filename_y);

 imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
 imagecopy($image, $image_y, $width_x, 0, 0, 0, $width_y, $height_y);

 // Save the resulting image to disk (as JPEG)

 imagejpeg($image, $filename_result);

 // Clean up

 imagedestroy($image);
 imagedestroy($image_x);
 imagedestroy($image_y);

}
Run Code Online (Sandbox Code Playgroud)

例:

merge('images/myimg.jpg', 'images/second.gif', 'images/merged.jpg');
Run Code Online (Sandbox Code Playgroud)