引言
准备工作
在开始之前,请确保您的服务器已安装PHP环境,并且安装了GD库,这是PHP处理图像的基础库。
步骤一:创建加水印函数
function addWatermark($sourceImage, $watermarkText, $fontFile, $fontSize, $angle, $x, $y, $color) {
// 创建图像资源
$image = imagecreatefromjpeg($sourceImage);
// 加载水印字体
$font = imagettfbbox($fontSize, $angle, $fontFile, $watermarkText);
// 计算水印位置
$width = $font[2] - $font[0];
$height = $font[7] - $font[1];
$x = ($imageWidth - $width) / 2;
$y = ($imageHeight - $height) / 2;
// 创建水印颜色
$watermarkColor = imagecolorallocate($image, $color[0], $color[1], $color[2]);
// 添加水印文本
imagettftext($image, $fontSize, $angle, $x, $y, $watermarkColor, $fontFile, $watermarkText);
// 输出加水印后的图片
header('Content-Type: image/jpeg');
imagejpeg($image);
// 释放资源
imagedestroy($image);
}
步骤二:调用函数
接下来,我们需要调用这个函数,传入相应的参数来添加水印。以下是一个示例:
$sourceImage = 'path/to/your/image.jpg'; // 源图片路径
$watermarkText = '版权所有'; // 水印文本
$fontFile = 'path/to/your/font.ttf'; // 字体文件路径
$fontSize = 20; // 字体大小
$angle = 0; // 字体倾斜角度
$x = 10; // 水印水平位置
$y = 10; // 水印垂直位置
$color = array(255, 255, 255); // 水印颜色(RGB)
addWatermark($sourceImage, $watermarkText, $fontFile, $fontSize, $angle, $x, $y, $color);