准备工作

在开始之前,请确保您的服务器已安装GD库,因为GD库是PHP处理图像的基础。以下是一些必要的准备工作:

  1. 安装GD库:确保您的PHP安装了GD库,可以通过运行 phpinfo() 函数来检查。
  2. 选择合适的图片格式:中文水印通常建议使用PNG格式,因为它支持透明度。
  3. 准备水印文字:确定您想要添加的水印文字内容。

添加中文水印的基本步骤

以下是添加中文水印的基本步骤:

1. 创建图像资源

$groundImage = imagecreatefrompng('path/to/your/image.png');

2. 设置字体和颜色

选择一个合适的字体文件,并设置水印的颜色。

$textFont = 'path/to/font.ttf'; // 字体文件的路径
$textColor = imagecolorallocate($groundImage, 255, 255, 255); // 白色

3. 添加水印文字

使用 imagettftext() 函数添加水印文字。此函数需要字体文件的路径、图像资源、文字内容、文字位置(x, y坐标)、字体大小和颜色。

imagettftext($groundImage, 20, 0, 10, 30, $textColor, $textFont, '版权所有');

4. 保存图像

最后,将带有水印的图像保存到文件中。

imagepng($groundImage, 'path/to/save/image.png');

5. 清理资源

处理完图像后,释放图像资源。

imagedestroy($groundImage);

代码示例

以下是一个完整的PHP脚本示例,展示了如何添加中文水印:

<?php
$groundImage = imagecreatefrompng('path/to/your/image.png');
$textFont = 'path/to/font.ttf';
$textColor = imagecolorallocate($groundImage, 255, 255, 255);

imagettftext($groundImage, 20, 0, 10, 30, $textColor, $textFont, '版权所有');

imagepng($groundImage, 'path/to/save/image.png');
imagedestroy($groundImage);
?>

总结