萬盛學電腦網

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

PHP 圖片浮水印實作:文字與圖片水印完整教學

為保護圖片版權或建立品牌辨識度,在圖片上添加浮水印是常見需求。PHP GD 函式庫提供 imagestring()(簡易文字)、imagettftext()(TrueType 字型文字)與 imagecopy()(圖片疊加)等函數,讓你輕鬆實作文字與圖片水印。本文詳細說明兩種水印模式的實作細節與進階技巧。

文字水印實作

<?php
function addTextWatermark(
    string $sourcePath,
    string $text,
    string $fontPath = '',
    int $fontSize = 20,
    array $color = [255, 0, 0],
    int $opacity = 50,      // 0-127,愈大愈透明
    int $position = 5,      // 1-9 九宮格位置
    int $margin = 10
): void {
    // 載入圖片(自動偵測格式)
    $ext = strtolower(pathinfo($sourcePath, PATHINFO_EXTENSION));
    $createFunc = match($ext) {
        'jpg', 'jpeg' => 'imagecreatefromjpeg',
        'png' => 'imagecreatefrompng',
        'gif' => 'imagecreatefromgif',
        'webp' => 'imagecreatefromwebp',
        default => throw new InvalidArgumentException("不支援的格式:$ext")
    };
    $img = $createFunc($sourcePath);
    
    // 啟用 Alpha 混合
    imagealphablending($img, true);
    imagesavealpha($img, true);
    
    // 分配水印顏色(含透明度)
    $watermarkColor = imagecolorallocatealpha($img, $color[0], $color[1], $color[2], $opacity);
    
    // 計算文字尺寸與位置
    $box = $fontPath 
        ? imagettfbbox($fontSize, 0, $fontPath, $text)
        : [0, 0, imagefontwidth(5) * strlen($text), imagefontheight(5)];
    
    $textWidth = $box[2] - $box[0];
    $textHeight = $box[1] - $box[7];
    
    $imgWidth = imagesx($img);
    $imgHeight = imagesy($img);
    
    // 九宮格位置計算
    $positions = [
        1 => [$margin, $margin + $textHeight],           // 左上
        2 => [($imgWidth - $textWidth) / 2, $margin + $textHeight], // 中上
        3 => [$imgWidth - $textWidth - $margin, $margin + $textHeight], // 右上
        4 => [$margin, ($imgHeight + $textHeight) / 2],  // 左中
        5 => [($imgWidth - $textWidth) / 2, ($imgHeight + $textHeight) / 2], // 正中
        6 => [$imgWidth - $textWidth - $margin, ($imgHeight + $textHeight) / 2], // 右中
        7 => [$margin, $imgHeight - $margin],            // 左下
        8 => [($imgWidth - $textWidth) / 2, $imgHeight - $margin], // 中下
        9 => [$imgWidth - $textWidth - $margin, $imgHeight - $margin], // 右下
    ];
    
    [$x, $y] = $positions[$position] ?? $positions[5];
    
    // 繪製文字
    if ($fontPath) {
        imagettftext($img, $fontSize, 0, $x, $y, $watermarkColor, $fontPath, $text);
    } else {
        imagestring($img, 5, $x, $y, $text, $watermarkColor);
    }
    
    // 輸出
    header('Content-Type: image/' . ($ext === 'jpg' ? 'jpeg' : $ext));
    $outputFunc = 'image' . ($ext === 'jpg' ? 'jpeg' : $ext);
    $outputFunc($img);
    imagedestroy($img);
}

// 使用範例
addTextWatermark('photo.jpg', '© MySite 2024', 'msjh.ttc', 24, [255,255,255], 40, 9);

圖片水印(Logo 疊加)實作

<?php
function addImageWatermark(
    string $sourcePath,
    string $watermarkPath,
    int $position = 9,      // 九宮格位置
    int $opacity = 50,      // 0-100 不透明度
    int $margin = 10
): void {
    // 載入主圖
    $mainExt = strtolower(pathinfo($sourcePath, PATHINFO_EXTENSION));
    $mainCreate = ['jpg'=>'imagecreatefromjpeg','jpeg'=>'imagecreatefromjpeg','png'=>'imagecreatefrompng','gif'=>'imagecreatefromgif','webp'=>'imagecreatefromwebp'][$mainExt] ?? null;
    if (!$mainCreate) throw new Exception("不支援的主圖格式");
    $mainImg = $mainCreate($sourcePath);
    
    // 載入水印圖(需為 PNG/WebP 含透明通道效果最佳)
    $wmExt = strtolower(pathinfo($watermarkPath, PATHINFO_EXTENSION));
    $wmCreate = ['png'=>'imagecreatefrompng','webp'=>'imagecreatefromwebp','gif'=>'imagecreatefromgif'][$wmExt] ?? null;
    if (!$wmCreate) throw new Exception("水印建議使用 PNG/WebP 格式");
    $wmImg = $wmCreate($watermarkPath);
    
    // 取得尺寸
    $mainW = imagesx($mainImg);
    $mainH = imagesy($mainImg);
    $wmW = imagesx($wmImg);
    $wmH = imagesy($wmImg);
    
    // 如果水印過大,自動縮放至主圖 30% 寬度
    if ($wmW > $mainW * 0.3) {
        $ratio = ($mainW * 0.3) / $wmW;
        $newW = (int)($wmW * $ratio);
        $newH = (int)($wmH * $ratio);
        $resized = imagecreatetruecolor($newW, $newH);
        imagealphablending($resized, false);
        imagesavealpha($resized, true);
        imagecopyresampled($resized, $wmImg, 0, 0, 0, 0, $newW, $newH, $wmW, $wmH);
        imagedestroy($wmImg);
        $wmImg = $resized;
        $wmW = $newW; $wmH = $newH;
    }
    
    // 位置計算(同九宮格)
    $positions = [
        1 => [$margin, $margin],
        2 => [($mainW - $wmW) / 2, $margin],
        3 => [$mainW - $wmW - $margin, $margin],
        4 => [$margin, ($mainH - $wmH) / 2],
        5 => [($mainW - $wmW) / 2, ($mainH - $wmH) / 2],
        6 => [$mainW - $wmW - $margin, ($mainH - $wmH) / 2],
        7 => [$margin, $mainH - $wmH - $margin],
        8 => [($mainW - $wmW) / 2, $mainH - $wmH - $margin],
        9 => [$mainW - $wmW - $margin, $mainH - $wmH - $margin],
    ];
    [$dstX, $dstY] = $positions[$position] ?? $positions[9];
    
    // 設定水印不透明度(需 PHP 5.5+)
    if (function_exists('imagecopymerge')) {
        imagecopymerge($mainImg, $wmImg, $dstX, $dstY, 0, 0, $wmW, $wmH, $opacity);
    } else {
        // 手動 Alpha 混合(舊版 PHP 相容)
        imagealphablending($mainImg, true);
        imagecopy($mainImg, $wmImg, $dstX, $dstY, 0, 0, $wmW, $wmH);
    }
    
    // 輸出
    header('Content-Type: image/' . ($mainExt === 'jpg' ? 'jpeg' : $mainExt));
    $outFunc = 'image' . ($mainExt === 'jpg' ? 'jpeg' : $mainExt);
    $outFunc($mainImg);
    
    imagedestroy($mainImg);
    imagedestroy($wmImg);
}

// 使用範例
addImageWatermark('photo.jpg', 'logo.png', 9, 60);

進階:批次處理資料夾內所有圖片

<?php
function batchWatermark(string $dir, string $watermark, string $outputDir, array $options = []): void {
    if (!is_dir($outputDir)) mkdir($outputDir, 0755, true);
    
    $files = glob($dir . '/*.{jpg,jpeg,png,gif,webp}', GLOB_BRACE);
    foreach ($files as $file) {
        $filename = basename($file);
        $outPath = $outputDir . '/' . $filename;
        
        // 這裡需修改上方函數改為儲存檔案而非直接輸出
        // 範例略...
        echo "處理:$filename\n";
    }
}

最佳實踐建議

  • 水印圖片格式:優先使用 PNG 或 WebP(支援 Alpha 透明通道),避免 JPEG 白底問題。
  • 字體檔案:中文水印必須指定 .ttf/.ttc 字體檔(如 msjh.ttc 微軟正黑體),並確保伺服器可讀取。
  • 效能考量:大量圖片處理建議使用 CLI 模式執行,避免 HTTP 超時;可搭配 pcntl_fork 或佇列系統並行處理。
  • 原圖保護:永遠在副本上操作,保留原始檔案;輸出時可考慮降低品質(imagejpeg($img, null, 85))節省頻寬。
  • 對角線平鋪水印:防盜圖需求可實作重複平鋪文字/圖片覆蓋全圖,增加去除難度。

常見問題 FAQ

Q: 水印文字出現亂碼/方框?
A: 必須使用 imagettftext() 搭配支援中文的 TTF 字體檔;確認字體檔路徑正確且可讀。
Q: PNG 透明背景變黑底?
A: 載入 PNG 後需啟用 imagealphablending($img, true); imagesavealpha($img, true);。
Q: 如何在 Nginx/Apache 直接攔截圖片請求自動加水印?
A: 使用 ngx_http_image_filter_module (Nginx) 或 mod_rewrite + PHP 腳本攔截,但建議應用層處理更靈活。
Q: 處理超大圖片 (>5000px) 記憶體不足?
A: 分塊處理或使用 ImageMagick convert 指令列工具(透過 exec() 調用),GD 受限於 PHP 記憶體限制。

浮水印不只是版權宣示,更是品牌曝光的免費廣告位。掌握 PHP GD 水印技術,讓你的圖片內容在傳播過程中自帶身分證明!

copyright © 萬盛學電腦網 all rights reserved