You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP使用imagecopy函数垂直合并两张PNG图片的方法咨询

实现PNG图片垂直合并的解决方案

要把两张PNG图片上下垂直拼接,只需要调整合并画布的尺寸和imagecopy()的坐标参数即可,核心修改点很明确,我给你改好完整代码并解释细节:

完整修改后的PHP代码片段

$img1_path = 'images/1.png';
$img2_path = 'images/2.png';

// 获取两张图片的尺寸信息
list($img1_width, $img1_height) = getimagesize($img1_path);
list($img2_width, $img2_height) = getimagesize($img2_path);

// 计算合并后图片的尺寸:宽度取两张中较大值,高度为两者之和
$merged_width = max($img1_width, $img2_width);
$merged_height = $img1_height + $img2_height;

// 创建支持透明的合并画布(适配PNG特性)
$merged_image = imagecreatetruecolor($merged_width, $merged_height);
imagealphablending($merged_image, false);
imagesavealpha($merged_image, true);

// 加载两张PNG图片资源
$img1 = imagecreatefrompng($img1_path);
$img2 = imagecreatefrompng($img2_path);

// 把第一张图片复制到合并画布的左上角
imagecopy($merged_image, $img1, 0, 0, 0, 0, $img1_width, $img1_height);

// 把第二张图片复制到第一张的底部(关键修改:y坐标设为第一张的高度)
imagecopy($merged_image, $img2, 0, $img1_height, 0, 0, $img2_width, $img2_height);

// 输出或保存合并后的图片
header('Content-Type: image/png');
imagepng($merged_image); // 直接在浏览器显示
// 也可以保存到本地文件:imagepng($merged_image, 'images/merged.png');

// 销毁资源释放内存
imagedestroy($img1);
imagedestroy($img2);
imagedestroy($merged_image);

关键修改说明

  • 合并画布尺寸调整:原来水平拼接时宽度是两者之和,现在垂直拼接需要宽度取最大值(避免某张图片被截断),高度改为两者高度相加(上下叠加的总高度)。
  • imagecopy()坐标修改:复制第二张图片时,目标y坐标从原来的0改成$img1_height,这样第二张图片就正好放在第一张的底部;x坐标保持0,保证两张图片左对齐。

这样就能完美实现你要的垂直上下拼接效果啦!

内容的提问来源于stack exchange,提问作者Ramalingam Perumal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:42:17