如何在运行时合并两个图像并保存在 php 中?

Posted

技术标签:

【中文标题】如何在运行时合并两个图像并保存在 php 中?【英文标题】:How to merge two images and save in php at Run Time? 【发布时间】:2012-07-04 13:50:15 【问题描述】:

我想在框架中上传图片并将图像和框架保存为单个图像,主要是框架中图像的大小,合并后在最终生成的图像中应该完全相同。 这是我的代码的一部分:

$imgframe = $_GET['imgframe'];
$imgphoto = $_GET['imgphoto'];

$imgwidth = $_GET['imgwidth'];
$imgheight = $_GET['imgheight'];

$imgleft = substr($_GET['imgleft'],0,-2);
$imgtop = substr($_GET['imgtop'],0, -2);

$src = imagecreatefromjpeg($imgphoto);//'image.jpg'
$dest = imagecreatefrompng($imgframe);//clip_image002.png

imagealphablending($dest, false);
imagesavealpha($dest, true);

imagecopyresampled( 
     $dest, $src, $imgleft, $imgtop, $imgleft, $imgtop,
     $imgwidth, $imgheight, $imgwidth, $imgheight
);

【问题讨论】:

您尝试过任何研究吗?这不是一个罕见的话题...***.com/search?q=%5Bphp%5D+merge+images 那么你这样做的具体问题是什么?向我们提供有关您想了解的更多详细信息。 如果我能再次对你投反对票,我会的。 根据框架大小动态保存图片有什么问题?! 获取框架大小?获取图像的大小?做必要的数学?保存图像?代码中有语法错误? 在保存最终图像时,它显示的高度与帧中显示的高度相同。我的问题是保存图像应该与帧中相同。但它看起来是部分主图像的快照..我想要根据大小的整个图像..!!希望你理解.. 所以需要调整图片大小;将其缩小到框架的大小。如何做到这一点取决于您使用的是 GD 还是 Imagick API。请将您尝试过的代码添加到您的问题中;没有看到代码,人们无法告诉你出了什么问题。另外,请尝试在 PHP 手册中搜索相关 API。最后,为了避免人们对您的问题投反对票,请阅读the SO guidlelines on a good question 和whathaveyoutried.com。本质上,总是发布有问题的代码 【参考方案1】:

根据您在问题下方的评论,您使用了错误的功能。

imagecopymerge 的 PHP 手册页声明它将图像的一部分复制到另一个图像上。它指出您可以指定要从源复制的区域的原点坐标、宽度和高度,以及放置该区域的目标坐标。

换句话说,它从源图像中取出一个给定大小的矩形区域,并将其放在目标顶部的给定位置。它不询问您要复制它的区域的大小,只询问位置。因此,它不会调整复制区域的大小,而是逐个像素地复制它。

你真正需要的函数是imagecopyresampled,它允许你指定目标区域的大小,并且会平滑地缩放源区域以适应。

编辑

您仍然遇到问题,因为您在源参数和目标参数中使用了相同的坐标和相同的尺寸。相同尺寸 == 无需调整大小。

$imgframe = $_GET['imgframe'];
$imgphoto = $_GET['imgphoto'];

// I am assuming these specify the area of the imgphoto which
// should be placed in the frame?
$imgwidth = $_GET['imgwidth'];
$imgheight = $_GET['imgheight'];
$imgleft = substr($_GET['imgleft'],0,-2);
$imgtop = substr($_GET['imgtop'],0, -2);

// now you also need to get the size of the frame so that
// you can resize the photo correctly:
$frameSize = getimagesize($imgframe);

$src = imagecreatefromjpeg($imgphoto);//'image.jpg'
$dest = imagecreatefrompng($imgframe);//clip_image002.png

imagealphablending($dest, false);
imagesavealpha($dest, true);

imagecopyresampled( 
     $dest, $src, 
     0, 0, // these two specify where in the DESTINATION you want to place the source.  You might want these to be offset by the width of the frame
     $imgleft, $imgtop, // the origin of area of the source you want to copy
     $frameSize[0], $frameSize[1], // These specify the size of the area that you want to copy IN TO (i.e., the size in the destination), again you might want to reduce these to take into account the width of the frame
     $imgwidth, $imgheight // the size of the area to copy FROM
);

【讨论】:

我已经应用了 imagecopyresampled() 但问题仍然存在。 那是因为您对源和目标使用了相同的维度!请参阅上面的编辑。

以上是关于如何在运行时合并两个图像并保存在 php 中?的主要内容,如果未能解决你的问题,请参考以下文章

如何在iOS中将重叠的贴纸与图像合并

如何在 Web 应用程序运行时合并两个查询并执行新创建的查询

用 PHP 合并两个图像

PHP将jpg图像分成两个相等的图像并保存

如何在 php 中保留图像裁剪时的透明颜色?(仅保存在 jpg 文件中)

上传时如何裁剪图像?