在php中合并两个图像


Merge two images in php

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

$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,但这并没有发生。也喜欢它是一个新的图像,并保存到另一个文件夹。

谢谢你的帮助。

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

例如:

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

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

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

Imagick是:

  • 更快
  • 了解更多格式
  • 制作质量更好的图像
  • 有更多的能力(例如文本旋转)
  • 还有更多

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

我找到了答案,使用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');