在php中合并两个图像

问题描述 投票:4回答:4

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

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

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

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

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

谢谢你的帮助。

php image image-processing gd
4个回答
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);

}

例:

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

0
投票

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

Imagick是:

  • 快点
  • 知道更多格式
  • 制作质量更好的图像
  • 有更多的能力(例如文字轮换)
  • 和更多...

如果你使用php模块,你的方法是Imagick :: compositeImage。手册:http://php.net/manual/en/function.imagick-compositeimage.php


0
投票

如果您使用的是PHP GD库,我想在这里再添加一件事,那么您还应该包括imagesavealpha()alphablending()


-4
投票

我找到了答案,使用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');
© www.soinside.com 2019 - 2024. All rights reserved.