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

PHP如何修复水印位置问题 实现5个自适应位置的图片水印添加

问题根源

你当前的左下角、右上角水印代码使用了固定像素值的边距($marge_right = 670、$marge_bottom = 430),当原图尺寸小于(边距+水印尺寸)时,计算出的水印坐标会为负数,导致水印被绘制到画布外消失,不同尺寸的图片下位置也无法统一。

修正方案

和你已验证可用的另外三个位置逻辑对齐,使用统一的边距规则即可实现全尺寸图片适配,以下是可直接使用的实现代码,边距默认统一为10px,可按需调整数值:


右上角(top_right)实现代码

$imgs = imagecreatefromjpeg("/var/www/$f$p/$n");
// 加载水印图片
$stamps = imagecreatefrompng("$waterpath/$watername");
// 边距设置,可按需调整数值
$marge_right = 10;
$marge_top = 10;

$sx = imagesx($stamps);
$sy = imagesy($stamps);
$imageWidth = imagesx($imgs);
$imageHeight = imagesy($imgs);

// 定位逻辑:x = 图片宽度 - 水印宽度 - 右侧边距,y = 顶部边距
imagecopy($imgs, $stamps, $imageWidth - $sx - $marge_right, $marge_top, 0, 0, imagesx($stamps), imagesy($stamps));

imagejpeg($imgs, "/var/www/$f$p/$n");

左下角(bottom_left)实现代码

$imgs = imagecreatefromjpeg("/var/www/$f$p/$n");
// 加载水印图片
$stamps = imagecreatefrompng("$waterpath/$watername");
// 边距设置,可按需调整数值
$marge_left = 10;
$marge_bottom = 10;

$sx = imagesx($stamps);
$sy = imagesy($stamps);
$imageWidth = imagesx($imgs);
$imageHeight = imagesy($imgs);

// 定位逻辑:x = 左侧边距,y = 图片高度 - 水印高度 - 底部边距
imagecopy($imgs, $stamps, $marge_left, $imageHeight - $sy - $marge_bottom, 0, 0, imagesx($stamps), imagesy($stamps));

imagejpeg($imgs, "/var/www/$f$p/$n");

如果你需要边距随图片尺寸等比缩放(和你现有左上角的实现逻辑一致),可以把固定边距替换为动态计算值,示例:
$marge_left = ($imageWidth - $sx) / 100;
$marge_top = ($imageHeight - $sy) / 100;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:30:01