在项目的开发中,通常需要我们给图片加上水印来防止盗图,以下是php程序给图片添加水印的方法,记录一下,方便下次使用
最终效果
- 原图
- 水印图
程序实现
- 缩放png图片,防止传入的水印图片大小不合适,可以用此方法调整水印大小
function zoomPng($origin, $target, $per)
{
$srcImg = imagecreatefrompng($origin);
$srcWidth = imagesx($srcImg);
$srcHeight = imagesy($srcImg);
$newWidth = round($srcWidth * $per);
$newHeight = round($srcHeight * $per);
$newImg = imagecreatetruecolor($newWidth, $newHeight);
$alpha = imagecolorallocatealpha($newImg, 0, 0, 0, 127);
imagefill($newImg, 0, 0, $alpha);
imagecopyresampled($newImg, $srcImg, 0, 0, 0, 0, $newWidth, $newHeight, $srcWidth, $srcHeight);
imagesavealpha($newImg, true);
imagepng($newImg, $target);
imagedestroy($newImg);
imagedestroy($srcImg);
}
- 添加水印方法,此方法是给图片添加满屏的水印,如果只需要一个水印,那么只需要将方法体中的for循环方法去掉,将里面的
imagecopyresampled 方法执行一遍即可
function addFillMark(string $originPath, string $markPath, string $targetPath): void
{
$info = getimagesize($originPath);
switch ($info['mime']) {
case 'image/png':
$originSource = imagecreatefrompng($originPath);
break;
case 'image/jpeg':
$originSource = imagecreatefromjpeg($originPath);
break;
case 'image/gif':
$originSource = imagecreatefromgif($originPath);
break;
}
$originWidth = $info[0];
$originHeight = $info[1];
$markSource = imagecreatefrompng($markPath);
$markWidth = imagesx($markSource);
$markHeight = imagesy($markSource);
for ($x = 0; $x < $originWidth; $x++) {
for ($y = 0; $y < $originHeight; $y++) {
imagecopyresampled($originSource, $markSource, $x, $y, 0, 0, $markWidth, $markHeight, $markWidth, $markHeight);
$y += $markHeight;
}
$x += $markWidth;
}
imagesavealpha($originSource, true);
switch ($info['mime']) {
case 'image/png':
imagepng($originSource, $targetPath);
break;
case 'image/jpeg':
imagejpeg($originSource, $targetPath);
break;
case 'image/gif':
imagegif($originSource, $targetPath);
break;
}
imagedestroy($markSource);
imagedestroy($originSource);
}
|