在PHP中合并两张图片

6

我有两张图片想要合并,然后保存到一个新的位置。
我希望第二张图片直接放在第一张图片下面。
目前我有以下代码,但是图片甚至没有保存。

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

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

// Copy and merge
imagecopymerge($destimg, $src, 316, 100, 0, 0, 316, 100, 100);

两张图片的宽度均为316像素x100像素

从上面的代码来看,$destimg现在应该是316x200,但实际上并没有发生。还希望它成为一个新的图像并保存到另一个文件夹中。

感谢您的任何帮助。


你看到了你的PHP版本和所需的版本了吗? - clement
谢谢回复。我在描述中添加了PHP 5,但我认为它被管理员删除了。 - john tully
合并垂直方向:https://stackoverflow.com/a/50045143/9370144 - Nadun Kulatunge
4个回答

20

在这种情况下,最好的方法可能是在内存中创建一个具有所需合并尺寸的新图像,然后将现有图像复制或重采样到新图像中,最后将新图像保存到磁盘。

例如:

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);

}

示例:

merge('images/myimg.jpg', 'images/second.gif', 'images/merged.jpg');

最好通过检查imagecreatetruecolor和imagecreatefromjpeg的结果来包含更好的错误处理。出于简洁起见,我忽略了这一点。 - Chris Hutchinson

1

如果您正在使用PHP GD库,那么您还应该包含imagesavealpha()alphablending()


0

我建议您使用Image Magick(pecl-imagick模块或通过shell运行它作为命令)。 我有几个理由:

Imagick具有以下优点:

  • 速度更快
  • 支持更多格式
  • 生成更高质量的图像
  • 具有更多功能(例如文本旋转)
  • 等等...

如果您使用php模块,则可以使用Imagick :: compositeImage方法。 手册:http://php.net/manual/en/function.imagick-compositeimage.php


-5

我找到答案了,使用GD:

 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, $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);
                        //  top, left, border,border
 imagecopy($image, $image_y, 100, 3100, 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);

}

像这样:

merge('images/myimage.jpg', 'images/second.gif', 'images/merged.jpg');

那个答案在上面。 - Andy Gee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接