一、准备工作
在开始之前,请确保你的服务器上已安装以下PHP扩展:
- GD库:用于图像处理。
- ImageMagick库(可选):提供更丰富的图像处理功能。
你可以通过以下命令检查GD库是否已安装:
php -m | grep gd
如果GD库未安装,请通过你的服务器管理界面或命令行进行安装。
二、创建水印函数
function addWatermark($imagePath, $watermarkText, $outputPath, $fontFile = 'arial.ttf', $fontSize = 20, $fontColor = array(255, 255, 255), $angle = 0, $position = 'bottom-right') {
// 加载图片
$image = imagecreatefromjpeg($imagePath);
// 创建水印文字
$fontColor = imagecolorallocate($image, $fontColor[0], $fontColor[1], $fontColor[2]);
$text = $watermarkText;
$textWidth = imagettfbbox($fontSize, $angle, $fontFile, $text);
$textWidth = $textWidth[2] - $textWidth[0];
$textHeight = $textWidth / 2;
// 计算水印位置
$x = 0;
$y = 0;
switch ($position) {
case 'top-left':
$x = 10;
$y = 10;
break;
case 'top-right':
$x = imagesx($image) - $textWidth - 10;
$y = 10;
break;
case 'bottom-left':
$x = 10;
$y = imagesy($image) - $textHeight - 10;
break;
case 'bottom-right':
$x = imagesx($image) - $textWidth - 10;
$y = imagesy($image) - $textHeight - 10;
break;
default:
$x = (imagesx($image) - $textWidth) / 2;
$y = (imagesy($image) - $textHeight) / 2;
break;
}
// 添加水印文字
imagettftext($image, $fontSize, $angle, $x, $y, $fontColor, $fontFile, $text);
// 保存图片
imagejpeg($image, $outputPath);
// 释放资源
imagedestroy($image);
}
三、使用水印函数
$imagePath = 'example.jpg'; // 图片路径
$watermarkText = '版权所有'; // 水印文字
$outputPath = 'output.jpg'; // 输出图片路径
$fontFile = 'arial.ttf'; // 字体文件路径
$fontSize = 20; // 字体大小
$fontColor = array(255, 255, 255); // 字体颜色(白色)
$angle = 0; // 字体倾斜角度
$position = 'bottom-right'; // 水印位置
addWatermark($imagePath, $watermarkText, $outputPath, $fontFile, $fontSize, $fontColor, $angle, $position);