引言

一、PHP水印制作基础

1.1 PHP环境搭建

在开始制作水印之前,确保你的计算机上已经安装了PHP环境。可以使用XAMPP、WAMP等集成开发环境进行快速搭建。

1.2 图像处理库

PHP提供了GD库用于图像处理,它是制作水印的基础。可以通过以下代码检查GD库是否已安装:

if (extension_loaded('gd')) {
    echo 'GD库已安装';
} else {
    echo 'GD库未安装,请安装GD库';
}

1.3 图片读取与设置

$sourceImage = imagecreatefromjpeg('path/to/image.jpg');
imagealphablending($sourceImage, true);
imagesavealpha($sourceImage, true);

二、添加文字水印

2.1 选择字体与颜色

在添加文字水印之前,需要选择合适的字体和颜色。PHP支持使用TrueType字体文件。以下代码示例展示了如何设置字体和颜色:

$fontFile = 'path/to/font.ttf';
$fontColor = imagecolorallocate($sourceImage, 255, 255, 255); // 白色

2.2 设置水印位置与内容

$text = '版权所有';
$fontSize = 20;
$textWidth = imagettfbbox($fontSize, 0, $fontFile, $text);
$textWidth = $textWidth[2] - $textWidth[0];
$textHeight = $textWidth / 4;

$width = imagesx($sourceImage);
$height = imagesy($sourceImage);
$x = $width - $textWidth - 10;
$y = $height - $textHeight - 10;

imagettftext($sourceImage, $fontSize, 0, $x, $y, $fontColor, $fontFile, $text);

三、添加图片水印

3.1 图片读取与缩放

$watermarkImage = imagecreatefrompng('path/to/watermark.png');
$watermarkWidth = imagesx($watermarkImage);
$watermarkHeight = imagesy($watermarkImage);
$scale = 0.1;
$watermarkImage = imagescale($watermarkImage, $watermarkWidth * $scale, $watermarkHeight * $scale);

3.2 设置水印位置

$width = imagesx($sourceImage);
$height = imagesy($sourceImage);
$x = $width - $watermarkWidth - 10;
$y = $height - $watermarkHeight - 10;

imagecopy($sourceImage, $watermarkImage, $x, $y, 0, 0, $watermarkWidth, $watermarkHeight);

四、平铺水印效果

4.1 创建平铺函数

为了实现平铺效果,需要创建一个平铺函数:

function tileWatermark($image, $watermark, $tileWidth, $tileHeight) {
    $width = imagesx($image);
    $height = imagesy($image);
    for ($x = 0; $x < $width; $x += $tileWidth) {
        for ($y = 0; $y < $height; $y += $tileHeight) {
            imagecopy($image, $watermark, $x, $y, 0, 0, $tileWidth, $tileHeight);
        }
    }
}

4.2 应用平铺效果

$tileWidth = 50;
$tileHeight = 50;
tileWatermark($sourceImage, $watermarkImage, $tileWidth, $tileHeight);

五、保存与输出图片

header('Content-Type: image/jpeg');
imagejpeg($sourceImage);

总结