准备工作

在开始之前,请确保你的服务器上已经安装了PHP和GD库。GD库是PHP中处理图像的一个扩展库,是添加水印文字的关键。

方法一:面向过程的编写方法

<?php
// 指定图片路径
$src = '001.png';
// 获取图片信息
$info = getimagesize($src);
// 获取图片扩展名
$ext = image_type_to_extension($info[2]);
// 动态的把图片导入内存中
$image = imagecreatefromstring(file_get_contents($src));

// 指定字体颜色
$col = imagecolorallocatealpha($image, 255, 255, 255, 50);

// 指定字体内容
$content = 'Hello World';

// 给图片添加文字
imagestring($image, 5, 20, 30, $content, $col);

// 指定输入类型
header('Content-type: image/' . $ext);

// 动态的输出图片到浏览器中
imagepng($image);

// 销毁图片
imagedestroy($image);
?>

方法二:面向对象的实现方法

面向对象的实现方法可以使代码更加清晰和易于维护。以下是一个使用面向对象的方法添加文字水印的示例:

<?php
class ImageWatermark {
    private $image;
    private $info;

    public function __construct($src) {
        $this->info = getimagesize($src);
        $this->image = imagecreatefromstring(file_get_contents($src));
    }

    public function addTextWatermark($content, $color, $fontSize, $x, $y) {
        $col = imagecolorallocatealpha($this->image, $color[0], $color[1], $color[2], 50);
        imagestring($this->image, $fontSize, $x, $y, $content, $col);
    }

    public function output() {
        $ext = image_type_to_extension($this->info[2]);
        header('Content-type: image/' . $ext);
        imagepng($this->image);
        imagedestroy($this->image);
    }
}

// 使用示例
$imageWatermark = new ImageWatermark('001.png');
$imageWatermark->addTextWatermark('Hello World', [255, 255, 255], 5, 20, 30);
$imageWatermark->output();
?>

总结