在php中合并两个图像
我有两张图像要合并,然后保存到新位置。在php中合并两个图像,php,image,image-processing,gd,Php,Image,Image Processing,Gd,我有两张图像要合并,然后保存到新位置。 我希望第二张图片直接放在第一张图片的下方。 我有以下内容,但图像甚至没有保存 $destimg = imagecreatefromjpeg('images/myimg.jpg'); $src = imagecreatefromgif('images/second.gif'); // Copy and merge imagecopymerge($destimg, $src, 316, 100, 0, 0, 316, 100, 100); 两幅图像的
我希望第二张图片直接放在第一张图片的下方。
我有以下内容,但图像甚至没有保存
$destimg = imagecreatefromjpeg('images/myimg.jpg');
$src = imagecreatefromgif('images/second.gif');
// Copy and merge
imagecopymerge($destimg, $src, 316, 100, 0, 0, 316, 100, 100);
两幅图像的宽度均为316px 100px根据上面的代码,$destimg现在应该是316x200,但这并没有发生。也希望它是一个新的图像,并保存到另一个文件夹
谢谢您的帮助。我建议您改用Image Magick(pecl imagick模块或通过shell以命令形式运行它)。我有几个理由: Imagick是:
- 更快
- 了解更多格式
- 制作质量更好的图像
- 具有更多功能(例如文本旋转)
- 还有更多
如果您使用php模块,那么您的方法是Imagick::compositeImage。手动:针对这种情况的最佳方法可能是在内存中创建一个具有所需组合尺寸的新映像,然后将现有映像复制或重新采样到新映像,然后将新映像保存到磁盘 例如:
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()
和alphabling()
我找到了答案,用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');
你看到你的PHP版本和需要的版本了吗?谢谢你的回复。我在描述中添加了PHP5,但我认为它是从mods中删除的。垂直合并:通过检查imagecreatetruecolor和imagecreatefromjpeg的结果来包含更好的错误处理是明智的。为了简洁起见,我忽略了这一点。答案就在上面。