PHP文字水印怎么加

wen PHP项目 2

本文目录导读:

PHP文字水印怎么加

  1. 基础文字水印(使用GD库)
  2. 支持中文字体
  3. 使用图片水印(文字转图片)
  4. 完整的功能封装
  5. 注意事项
  6. 优化建议

在PHP中添加文字水印,最常用的方法是使用GD库,下面是几种常见的实现方式:

基础文字水印(使用GD库)

<?php
function addTextWatermark($sourceImage, $watermarkText, $outputImage = null) {
    // 获取图片信息
    $imageInfo = getimagesize($sourceImage);
    $imageType = $imageInfo[2];
    // 根据图片类型创建图像
    switch ($imageType) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($sourceImage);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($sourceImage);
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($sourceImage);
            break;
        default:
            return false;
    }
    // 设置水印文字颜色(白色,带透明度)
    $textColor = imagecolorallocatealpha($image, 255, 255, 255, 50);
    // 文字路径和大小
    $fontSize = 30;
    $fontPath = './arial.ttf'; // 确保这个字体文件存在
    // 获取图片宽高
    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);
    // 文字位置(右下角)
    $x = $imageWidth - 200;
    $y = $imageHeight - 50;
    // 添加文字水印
    imagettftext($image, $fontSize, 0, $x, $y, $textColor, $fontPath, $watermarkText);
    // 输出图片
    $output = $outputImage ?: $sourceImage;
    switch ($imageType) {
        case IMAGETYPE_JPEG:
            imagejpeg($image, $output);
            break;
        case IMAGETYPE_PNG:
            imagepng($image, $output);
            break;
        case IMAGETYPE_GIF:
            imagegif($image, $output);
            break;
    }
    // 释放内存
    imagedestroy($image);
    return true;
}
// 使用示例
addTextWatermark('original.jpg', '© 2024', 'watermarked.jpg');
?>

支持中文字体

<?php
function addChineseWatermark($sourceImage, $watermarkText, $outputImage = null) {
    $imageInfo = getimagesize($sourceImage);
    $imageType = $imageInfo[2];
    switch ($imageType) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($sourceImage);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($sourceImage);
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($sourceImage);
            break;
        default:
            return false;
    }
    // 设置水印颜色
    $textColor = imagecolorallocate($image, 255, 255, 255);
    // 中文字体路径(需要用支持中文的字体)
    $fontSize = 28;
    $fontPath = './msyh.ttf'; // 微软雅黑字体文件
    // 获取文字边界框
    $bbox = imagettfbbox($fontSize, 0, $fontPath, $watermarkText);
    $textWidth = abs($bbox[2] - $bbox[0]);
    $textHeight = abs($bbox[7] - $bbox[1]);
    // 位置(居中)
    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);
    $x = ($imageWidth - $textWidth) / 2;
    $y = ($imageHeight - $textHeight) / 2;
    // 添加水印
    imagettftext($image, $fontSize, 0, $x, $y, $textColor, $fontPath, $watermarkText);
    // 保存图片
    $output = $outputImage ?: $sourceImage;
    if ($imageType == IMAGETYPE_JPEG) {
        imagejpeg($image, $output, 90);
    } elseif ($imageType == IMAGETYPE_PNG) {
        imagepng($image, $output);
    }
    imagedestroy($image);
    return true;
}
?>

使用图片水印(文字转图片)

<?php
function createTextImageWatermark($text, $width = 200, $height = 80) {
    // 创建透明画布
    $image = imagecreatetruecolor($width, $height);
    imagesavealpha($image, true);
    // 设置透明背景
    $transparentColor = imagecolorallocatealpha($image, 0, 0, 0, 127);
    imagefill($image, 0, 0, $transparentColor);
    // 文字颜色(半透明)
    $textColor = imagecolorallocate($image, 255, 255, 255);
    // 添加文字
    $fontSize = 20;
    $fontPath = './arial.ttf';
    imagettftext($image, $fontSize, 0, 10, 50, $textColor, $fontPath, $text);
    return $image;
}
function addImageWatermarkToPhoto($sourceImage, $watermarkImage) {
    $imageInfo = getimagesize($sourceImage);
    $imageType = $imageInfo[2];
    // 加载原图
    switch ($imageType) {
        case IMAGETYPE_JPEG:
            $image = imagecreatefromjpeg($sourceImage);
            break;
        case IMAGETYPE_PNG:
            $image = imagecreatefrompng($sourceImage);
            break;
        case IMAGETYPE_GIF:
            $image = imagecreatefromgif($sourceImage);
            break;
    }
    // 水印位置(右下角)
    $imageWidth = imagesx($image);
    $imageHeight = imagesy($image);
    $watermarkWidth = imagesx($watermarkImage);
    $watermarkHeight = imagesy($watermarkImage);
    $x = $imageWidth - $watermarkWidth - 20;
    $y = $imageHeight - $watermarkHeight - 20;
    // 合并水印
    imagecopy($image, $watermarkImage, $x, $y, 0, 0, $watermarkWidth, $watermarkHeight);
    // 保存
    imagejpeg($image, 'watermarked.jpg', 90);
    imagedestroy($image);
    imagedestroy($watermarkImage);
}
// 使用示例
$watermark = createTextImageWatermark('© 2024');
addImageWatermarkToPhoto('original.jpg', $watermark);
?>

完整的功能封装

<?php
class WatermarkHandler {
    private $fontPath;
    private $uploadsDir;
    public function __construct($fontPath = './arial.ttf', $uploadsDir = './uploads/') {
        $this->fontPath = $fontPath;
        $this->uploadsDir = $uploadsDir;
    }
    /**
     * 添加文字水印
     */
    public function addTextWatermark($sourcePath, $text, $options = []) {
        $defaults = [
            'fontSize' => 30,
            'angle' => 0,
            'opacity' => 50,
            'color' => [255, 255, 255],
            'position' => 'bottom_right', // top_left, top_right, bottom_left, bottom_right, center
            'margin' => 20,
            'quality' => 90
        ];
        $options = array_merge($defaults, $options);
        try {
            // 加载图片
            $image = $this->loadImage($sourcePath);
            if (!$image) return false;
            $imageInfo = getimagesize($sourcePath);
            $imageType = $imageInfo[2];
            // 创建颜色
            $color = $options['color'];
            $textColor = imagecolorallocatealpha(
                $image, 
                $color[0], 
                $color[1], 
                $color[2], 
                $options['opacity']
            );
            // 计算文字尺寸
            $bbox = imagettfbbox($options['fontSize'], 0, $this->fontPath, $text);
            $textWidth = abs($bbox[2] - $bbox[0]);
            $textHeight = abs($bbox[7] - $bbox[1]);
            // 计算位置
            list($x, $y) = $this->calculatePosition(
                $options['position'],
                $imageInfo[0], $imageInfo[1],
                $textWidth, $textHeight,
                $options['margin']
            );
            // 添加水印
            imagettftext(
                $image, 
                $options['fontSize'], 
                $options['angle'], 
                $x, $y, 
                $textColor, 
                $this->fontPath, 
                $text
            );
            // 保存输出
            $outputPath = isset($options['output']) ? $options['output'] : $sourcePath;
            $this->saveImage($image, $outputPath, $imageType, $options['quality']);
            imagedestroy($image);
            return true;
        } catch (Exception $e) {
            error_log('水印添加失败: ' . $e->getMessage());
            return false;
        }
    }
    /**
     * 计算水印位置
     */
    private function calculatePosition($position, $imgWidth, $imgHeight, $textWidth, $textHeight, $margin) {
        switch ($position) {
            case 'top_left':
                return [$margin, $textHeight];
            case 'top_right':
                return [$imgWidth - $textWidth - $margin, $textHeight];
            case 'bottom_left':
                return [$margin, $imgHeight - $margin];
            case 'center':
                return [($imgWidth - $textWidth) / 2, ($imgHeight - $textHeight) / 2];
            case 'bottom_right':
            default:
                return [$imgWidth - $textWidth - $margin, $imgHeight - $margin];
        }
    }
    /**
     * 加载图片
     */
    private function loadImage($path) {
        $imageInfo = getimagesize($path);
        switch ($imageInfo[2]) {
            case IMAGETYPE_JPEG:
                return imagecreatefromjpeg($path);
            case IMAGETYPE_PNG:
                return imagecreatefrompng($path);
            case IMAGETYPE_GIF:
                return imagecreatefromgif($path);
            default:
                return null;
        }
    }
    /**
     * 保存图片
     */
    private function saveImage($image, $path, $imageType, $quality) {
        switch ($imageType) {
            case IMAGETYPE_JPEG:
                return imagejpeg($image, $path, $quality);
            case IMAGETYPE_PNG:
                return imagepng($image, $path);
            case IMAGETYPE_GIF:
                return imagegif($image, $path);
        }
    }
}
// 使用示例
$handler = new WatermarkHandler('./font/msyh.ttf');
$success = $handler->addTextWatermark(
    'original.jpg',
    '© 2024 My Website',
    [
        'fontSize' => 28,
        'position' => 'bottom_right',
        'opacity' => 40,
        'output' => 'watermarked.jpg'
    ]
);
if ($success) {
    echo "水印添加成功!";
} else {
    echo "水印添加失败!";
}
?>

注意事项

  1. 字体文件:使用 imagettftext() 需要指定一个有效的TTF字体文件
  2. 中文支持:使用支持中文的字体文件(如微软雅黑、SimHei等)
  3. 图片权限:确保图片文件可读写
  4. 输出格式:PNG图片会丢失JPEG的行压缩数据,建议保持原格式

优化建议

  • 对于大图片,可以先缩放再添加水印
  • 使用半透明效果可以更好地避免遮挡原图内容
  • 考虑添加多个水印或多个位置来防止盗图
  • 可以添加时间戳或用户ID来追踪图片来源

这样就能很好地完成PHP文字水印的功能了!

抱歉,评论功能暂时关闭!