萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 給圖片添加水印完整實作 (文字/圖片水印、九宮格位置、透明度、縮略圖)

核心類別:Watermarker

<?php
class Watermarker {
    private $srcImage;
    private $width;
    private $height;
    private $mime;

    public function __construct(string $sourcePath) {
        if (!file_exists($sourcePath)) throw new Exception("來源圖片不存在: $sourcePath");
        $info = getimagesize($sourcePath);
        $this->width = $info[0];
        $this->height = $info[1];
        $this->mime = $info['mime'];

        switch ($this->mime) {
            case 'image/jpeg': $this->srcImage = imagecreatefromjpeg($sourcePath); break;
            case 'image/png':  $this->srcImage = imagecreatefrompng($sourcePath); break;
            case 'image/gif':  $this->srcImage = imagecreatefromgif($sourcePath); break;
            case 'image/webp': $this->srcImage = imagecreatefromwebp($sourcePath); break;
            default: throw new Exception("不支援的圖片格式: {$this->mime}");
        }
        // 保持透明度 (PNG/GIF/WEBP)
        if (in_array($this->mime, ['image/png','image/gif','image/webp'])) {
            imagealphablending($this->srcImage, true);
            imagesavealpha($this->srcImage, true);
        }
    }

    /** 計算水印位置座標 */
    private function calcPosition(int $wmW, int $wmH, int $pos = 5, int $margin = 10): array {
        $positions = [
            1 => [$margin, $this->height - $wmH - $margin],           // 左下
            2 => [$this->width - $wmW - $margin, $this->height - $wmH - $margin], // 右下
            3 => [$margin, $margin],                                   // 左上
            4 => [$this->width - $wmW - $margin, $margin],             // 右上
            5 => [($this->width - $wmW)/2, ($this->height - $wmH)/2],  // 居中
            6 => [$margin, ($this->height - $wmH)/2],                  // 左中
            7 => [$this->width - $wmW - $margin, ($this->height - $wmH)/2], // 右中
            8 => [($this->width - $wmW)/2, $margin],                   // 上中
            9 => [($this->width - $wmW)/2, $this->height - $wmH - $margin], // 下中
        ];
        return $positions[$pos] ?? $positions[5];
    }

    /** 添加文字水印 */
    public function addText(string $text, int $fontSize = 20, string $color = '#FFFFFF', int $opacity = 50, int $position = 5, int $margin = 10, string $fontPath = ''): self {
        if (!$fontPath) $fontPath = __DIR__ . '/fonts/msyh.ttc'; // 需提供微軟雅黑或思源黑體 TTF
        if (!file_exists($fontPath)) throw new Exception("字體檔案不存在: $fontPath");

        // 建立水印圖層 (透明畫布)
        $box = imagettfbbox($fontSize, 0, $fontPath, $text);
        $wmW = $box[2] - $box[0] + 10; // 留白
        $wmH = $box[3] - $box[5] + 10;
        $wmImg = imagecreatetruecolor($wmW, $wmH);
        imagealphablending($wmImg, false);
        $transparent = imagecolorallocatealpha($wmImg, 0,0,0,127);
        imagefill($wmImg, 0, 0, $transparent);
        imagesavealpha($wmImg, true);

        // 解析顏色
        $hex = ltrim($color, '#');
        $rgb = strlen($hex) === 3 ? str_repeat($hex, 2) : $hex;
        $r = hexdec($rgb[0].$rgb[1]);
        $g = hexdec($rgb[2].$rgb[3]);
        $b = hexdec($rgb[4].$rgb[5]);
        $alpha = (int)(127 * (100 - $opacity) / 100); // 0 不透明, 127 全透明
        $textColor = imagecolorallocatealpha($wmImg, $r, $g, $b, $alpha);

        // 繪製文字到水印圖層
        imagettftext($wmImg, $fontSize, 0, 5, $wmH - 5, $textColor, $fontPath, $text);

        // 合成
        [$x, $y] = $this->calcPosition($wmW, $wmH, $position, $margin);
        imagecopy($this->srcImage, $wmImg, $x, $y, 0, 0, $wmW, $wmH);
        imagedestroy($wmImg);
        return $this;
    }

    /** 添加圖片水印 (支援 PNG 透明) */
    public function addImage(string $watermarkPath, int $position = 5, int $margin = 10, int $opacity = 50, float $scale = 1.0): self {
        if (!file_exists($watermarkPath)) throw new Exception("水印圖片不存在: $watermarkPath");
        $wmInfo = getimagesize($watermarkPath);
        $wmMime = $wmInfo['mime'];
        $wmSrc = match($wmMime) {
            'image/jpeg' => imagecreatefromjpeg($watermarkPath),
            'image/png'  => imagecreatefrompng($watermarkPath),
            'image/gif'  => imagecreatefromgif($watermarkPath),
            'image/webp' => imagecreatefromwebp($watermarkPath),
            default => throw new Exception("水印格式不支援: $wmMime"),
        };
        $wmW = (int)($wmInfo[0] * $scale);
        $wmH = (int)($wmInfo[1] * $scale);

        // 縮放水印 (保持透明)
        $wmImg = imagecreatetruecolor($wmW, $wmH);
        imagealphablending($wmImg, false);
        $transparent = imagecolorallocatealpha($wmImg, 0,0,0,127);
        imagefill($wmImg, 0, 0, $transparent);
        imagesavealpha($wmImg, true);
        imagecopyresampled($wmImg, $wmSrc, 0, 0, 0, 0, $wmW, $wmH, $wmInfo[0], $wmInfo[1]);
        imagedestroy($wmSrc);

        // 透明度調整
        if ($opacity < 100) {
            $alpha = (int)(127 * (100 - $opacity) / 100);
            imagefilter($wmImg, IMG_FILTER_COLORIZE, 0, 0, 0, $alpha);
        }

        [$x, $y] = $this->calcPosition($wmW, $wmH, $position, $margin);
        imagecopy($this->srcImage, $wmImg, $x, $y, 0, 0, $wmW, $wmH);
        imagedestroy($wmImg);
        return $this;
    }

    /** 生成縮略圖 (等比縮放) */
    public function thumbnail(int $maxW, int $maxH): self {
        $ratio = min($maxW / $this->width, $maxH / $this->height);
        if ($ratio >= 1) return $this; // 無需縮放
        $newW = (int)($this->width * $ratio);
        $newH = (int)($this->height * $ratio);
        $thumb = imagecreatetruecolor($newW, $newH);
        if (in_array($this->mime, ['image/png','image/gif','image/webp'])) {
            imagealphablending($thumb, false);
            $transparent = imagecolorallocatealpha($thumb, 0,0,0,127);
            imagefill($thumb, 0, 0, $transparent);
            imagesavealpha($thumb, true);
        }
        imagecopyresampled($thumb, $this->srcImage, 0, 0, 0, 0, $newW, $newH, $this->width, $this->height);
        imagedestroy($this->srcImage);
        $this->srcImage = $thumb;
        $this->width = $newW;
        $this->height = $newH;
        return $this;
    }

    /** 輸出/儲存 */
    public function save(string $destPath, int $quality = 90): bool {
        $ext = strtolower(pathinfo($destPath, PATHINFO_EXTENSION));
        $result = match($ext) {
            'jpg', 'jpeg' => imagejpeg($this->srcImage, $destPath, $quality),
            'png' => imagepng($this->srcImage, $destPath, (int)($quality/10)), // PNG quality 0-9
            'webp' => imagewebp($this->srcImage, $destPath, $quality),
            default => false,
        };
        return $result;
    }

    public function output(int $quality = 90): void {
        header('Content-Type: ' . $this->mime);
        switch ($this->mime) {
            case 'image/jpeg': imagejpeg($this->srcImage, null, $quality); break;
            case 'image/png':  imagepng($this->srcImage, null, (int)($quality/10)); break;
            case 'image/webp': imagewebp($this->srcImage, null, $quality); break;
        }
    }

    public function __destruct() {
        if (is_resource($this->srcImage)) imagedestroy($this->srcImage);
    }
}

使用範例

<?php
require 'Watermarker.php';

$source = 'photos/original.jpg';
$dest   = 'photos/watermarked.jpg';

try {
    $wm = new Watermarker($source);
    // 文字水印:右下角,白色 50% 透明度,24px
    $wm->addText('© MySite.com', 24, '#FFFFFF', 50, 2, 15);
    // 圖片水印:左上角,Logo,30% 透明度,縮放 0.3
    $wm->addImage('assets/logo.png', 3, 15, 30, 0.3);
    // 可選:生成縮略圖
    // $wm->thumbnail(800, 600);
    $wm->save($dest, 90);
    echo "水印添加成功: $dest";
} catch (Exception $e) {
    echo "錯誤: " . $e->getMessage();
}

批量處理腳本 (CLI)

<?php
// batch_watermark.php
$dir = $argv[1] ?? '.';
$files = glob("$dir/*.{jpg,jpeg,png,webp}", GLOB_BRACE);
foreach ($files as $file) {
    $out = preg_replace('/(\.[^.]+)$/', '_wm$1', $file);
    try {
        (new Watermarker($file))
            ->addText('© ' . date('Y'), 20, '#FFFFFF', 40, 2, 10)
            ->save($out, 85);
        echo "✅ $file -> $out\n";
    } catch (Exception $e) {
        echo "❌ $file: " . $e->getMessage() . "\n";
    }
}
php batch_watermark.php /var/www/images

效能與替代方案

方案優點缺點適用場景
GD (本文)內建、無依賴、支援基本需求大圖記憶體高、功能有限中小圖、簡單水印、共享主機
Imagick (ImageMagick)功能強大、效能好、支援向量、CMYK需安裝擴展、記憶體洩漏風險專業圖片處理、高併發、大圖
前端 Canvas零後端壓力、即時預覽需現代瀏覽器、原圖需下載到瀏覽器用戶上傳前預覽、輕量應用
雲端圖片處理 (Imgix/Cloudinary/阿里雲 OSS 圖片處理)無維護、CDN 加速、參數化 URL 即時處理費用、資料外傳生產環境首選、大流量
copyright © 萬盛學電腦網 all rights reserved