萬盛學電腦網

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

PHP 圖片加浮水印完整實作:GD 库支援多位置、透明度、GIF 動圖與自動縮放

核心功能需求

  • 支援 JPG/PNG/GIF/WebP 格式
  • 浮水印圖片自動縮放 (不超過原圖)
  • 9 種預設位置 + 隨機位置
  • 透明度控制 (0-100%)
  • 保持原圖格式與品質
  • 記憶體釋放防洩漏

完整類別實作

class ImageWatermark {
    private $sourceImage;
    private $watermarkImage;
    private $wmWidth;
    private $wmHeight;
    private $wmType; // jpeg, png, gif, webp
    
    public function __construct(string $sourcePath) {
        $this->sourceImage = $this->loadImage($sourcePath);
        if (!$this->sourceImage) throw new Exception("無法載入原圖: $sourcePath");
    }
    
    public function addWatermark(
        string $watermarkPath,
        int $position = 5,      // 1-9 九宮格,0=隨機
        int $opacity = 80,      // 0-100
        int $margin = 10        // 邊距
    ): bool {
        $this->loadWatermark($watermarkPath);
        $this->calculatePosition($position, $margin);
        $this->applyWatermark($opacity);
        return $this->save($this->sourceImage);
    }
    
    private function loadImage(string $path) {
        $info = getimagesize($path);
        if (!$info) return false;
        
        $type = strtolower(image_type_to_extension($info[2], false)); // jpeg, png, gif, webp
        $func = "imagecreatefrom$type";
        if (!function_exists($func)) return false;
        
        return $func($path);
    }
    
    private function loadWatermark(string $path) {
        $info = getimagesize($path);
        $this->wmWidth  = $info[0];
        $this->wmHeight = $info[1];
        $this->wmType   = strtolower(image_type_to_extension($info[2], false));
        $func = "imagecreatefrom{$this->wmType}";
        $this->watermarkImage = $func($path);
        
        // 自動縮放:不超過原圖 50%
        $srcW = imagesx($this->sourceImage);
        $srcH = imagesy($this->sourceImage);
        if ($this->wmWidth > $srcW * 0.5 || $this->wmHeight > $srcH * 0.5) {
            $scale = min($srcW * 0.5 / $this->wmWidth, $srcH * 0.5 / $this->wmHeight);
            $newW = (int)($this->wmWidth * $scale);
            $newH = (int)($this->wmHeight * $scale);
            $resized = imagecreatetruecolor($newW, $newH);
            imagealphablending($resized, false);
            imagesavealpha($resized, true);
            imagecopyresampled($resized, $this->watermarkImage, 0, 0, 0, 0, $newW, $newH, $this->wmWidth, $this->wmHeight);
            imagedestroy($this->watermarkImage);
            $this->watermarkImage = $resized;
            $this->wmWidth = $newW;
            $this->wmHeight = $newH;
        }
    }
    
    private function calculatePosition(int $pos, int $margin) {
        $srcW = imagesx($this->sourceImage);
        $srcH = imagesy($this->sourceImage);
        
        $positions = [
            1 => [$margin, $margin],                                    // 左上
            2 => [($srcW - $this->wmWidth) / 2, $margin],              // 中上
            3 => [$srcW - $this->wmWidth - $margin, $margin],          // 右上
            4 => [$margin, ($srcH - $this->wmHeight) / 2],             // 左中
            5 => [($srcW - $this->wmWidth) / 2, ($srcH - $this->wmHeight) / 2], // 正中
            6 => [$srcW - $this->wmWidth - $margin, ($srcH - $this->wmHeight) / 2], // 右中
            7 => [$margin, $srcH - $this->wmHeight - $margin],         // 左下
            8 => [($srcW - $this->wmWidth) / 2, $srcH - $this->wmHeight - $margin], // 中下
            9 => [$srcW - $this->wmWidth - $margin, $srcH - $this->wmHeight - $margin], // 右下
        ];
        
        if ($pos === 0 || !isset($positions[$pos])) {
            $this->posX = rand($margin, $srcW - $this->wmWidth - $margin);
            $this->posY = rand($margin, $srcH - $this->wmHeight - $margin);
        } else {
            [$this->posX, $this->posY] = $positions[$pos];
        }
        $this->posX = max(0, (int)$this->posX);
        $this->posY = max(0, (int)$this->posY);
    }
    
    private function applyWatermark(int $opacity) {
        imagealphablending($this->sourceImage, true);
        imagecopymerge(
            $this->sourceImage, 
            $this->watermarkImage, 
            $this->posX, $this->posY, 
            0, 0, 
            $this->wmWidth, $this->wmHeight, 
            $opacity
        );
    }
    
    private function save($image): bool {
        $srcInfo = getimagesize($this->sourcePath ?? '');
        $type = $srcInfo[2] ?? IMAGETYPE_JPEG;
        $func = 'image' . image_type_to_extension($type, false);
        $quality = ($type === IMAGETYPE_JPEG) ? 90 : null;
        
        // 輸出到暫存檔再覆蓋,避免寫入中斷損壞原檔
        $tmp = tempnam(sys_get_temp_dir(), 'wm_');
        $saved = $quality ? $func($image, $tmp, $quality) : $func($image, $tmp);
        if ($saved && $this->sourcePath) {
            rename($tmp, $this->sourcePath);
        } elseif (!$saved) {
            @unlink($tmp);
        }
        imagedestroy($image);
        imagedestroy($this->watermarkImage);
        return $saved;
    }
}

// 使用範例
$wm = new ImageWatermark('photo.jpg');
$wm->addWatermark('logo.png', 9, 50); // 右下角、50% 透明度

GIF 動畫浮水印特殊處理

GD 庫**不支援**保持 GIF 動畫幀。需使用 ImageMagick (imagick 擴展):

function watermarkGif(string $source, string $watermark, string $output) {
    $animation = new Imagick();
    $animation->readImages($source); // 讀取所有幀
    
    $watermarkImg = new Imagick($watermark);
    
    foreach ($animation as $frame) {
        $frame->compositeImage($watermarkImg, Imagick::COMPOSITE_OVER, 10, 10);
    }
    
    $animation->writeImages($output, true); // true = 多幀
}

效能與記憶體優化

  • 大圖分塊處理 (imagecopyresampled 分段)
  • 處理完立即 imagedestroy()
  • 批次處理用 CLI 避免記憶體限制
  • 考慮 imagecreatetruecolor vs imagecreate (真彩色 vs 調色盤)

現代替代:Intervention Image

use Intervention\Image\ImageManagerStatic as Image;

Image::make('photo.jpg')
    ->insert('logo.png', 'bottom-right', 10, 10)
    ->save('output.jpg');
copyright © 萬盛學電腦網 all rights reserved