别哭爱我 发表于 2025-4-21 16:43:07

PHP 怎样实现图片平铺与倾斜水印效果?看这篇优化代码!

// 图片和水印文件路径

$img = 'test.jpg';

$source = 'source.png';

// 参数设置,值越大水印越稀(水印平铺的越少)

$ww = 0;  // 每个水印的左右间距

$hh = 0;  // 每个水印的上下间距

// 水印图片旋转角度

$angle = 30;

// 水印透明度

$opacity = 20;

// 获取图片和水印的信息

$imgInfo = getimagesize($img);

$sourceInfo = getimagesize($source);

// 创建水印图像资源

$waterFun = 'imagecreatefrom' . image_type_to_extension($sourceInfo, false);

$water = $waterFun($source);

// 水印图片旋转

$water = imagerotate($water, $angle, imageColorAllocateAlpha($water, 0, 0, 0, 127));

// 获取水印图片旋转后的宽度和高度

$waterWidth = imagesx($water);

$waterHeight = imagesy($water);

// 设定水印图像的混色模式

imagealphablending($water, true);

// 创建图片图像资源

$imgFun = 'imagecreatefrom' . image_type_to_extension($imgInfo, false);

$thumb = $imgFun($img);

// 定义平铺数据

$xLength = $imgInfo - 10; // x轴总长度

$yLength = $imgInfo - 10; // y轴总长度

// 循环平铺水印

for ($x = 0; $x < $xLength; $x += $waterWidth + $ww) {

for ($y = 0; $y < $yLength; $y += $waterHeight + $hh) {

imagecopymerge($thumb, $water, $x, $y, 0, 0, $waterWidth, $waterHeight, $opacity);

}

}

// 输出图片

header("Content-type: " . $imgInfo['mime']);

$outputFunction = 'image' . image_type_to_extension($imgInfo, false);

$outputFunction($thumb);

// 销毁图片资源

imagedestroy($thumb);

// 销毁水印资源

imagedestroy($water);   
页: [1]
查看完整版本: PHP 怎样实现图片平铺与倾斜水印效果?看这篇优化代码!