萬盛學電腦網

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

PHP GD 庫生成縮圖完整實作:等比縮放、多格式支援、品質控制

核心邏輯:計算目標尺寸

$info = getimagesize($sourcePath);
$srcW = $info[0];
$srcH = $info[1];
$mime = $info['mime'];

// 目標最大尺寸
$maxW = 100;
$maxH = 120;

// 計算縮放比例
$ratio = min($maxW / $srcW, $maxH / $srcH);
$dstW = (int)round($srcW * $ratio);
$dstH = (int)round($srcH * $ratio);

// 若原圖較小,不放大
if ($ratio >= 1) {
    $dstW = $srcW;
    $dstH = $srcH;
}

完整 makethumb2() 函數

/**
 * 生成縮圖
 * @param string $srcFile  來源圖片路徑
 * @param string $dstFile  目標圖片路徑
 * @param int    $dstW     目標寬度
 * @param int    $dstH     目標高度
 * @param int    $quality  JPEG 品質 0-100
 * @return bool
 */
function makethumb2($srcFile, $dstFile, $dstW, $dstH, $quality = 85) {
    if (!file_exists($srcFile)) return false;
    
    $info = @getimagesize($srcFile);
    if (!$info) return false;
    
    $srcW = $info[0];
    $srcH = $info[1];
    $mime = $info['mime'];
    
    // 建立來源圖片資源
    switch ($mime) {
        case 'image/gif':  $src = @imagecreatefromgif($srcFile); break;
        case 'image/jpeg': $src = @imagecreatefromjpeg($srcFile); break;
        case 'image/png':  $src = @imagecreatefrompng($srcFile); break;
        case 'image/webp': $src = @imagecreatefromwebp($srcFile); break;
        case 'image/bmp':  $src = @imagecreatefrombmp($srcFile); break;
        default: return false;
    }
    if (!$src) return false;
    
    // 建立目標畫布 (TrueColor)
    $dst = imagecreatetruecolor($dstW, $dstH);
    
    // PNG/GIF/WEBP 保留透明度
    if (in_array($mime, ['image/png','image/gif','image/webp'])) {
        imagealphablending($dst, false);
        imagesavealpha($dst, true);
        $transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);
        imagefill($dst, 0, 0, $transparent);
    }
    
    // 核心:重採樣縮放 (高品質)
    if (!imagecopyresampled($dst, $src, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH)) {
        imagedestroy($src);
        imagedestroy($dst);
        return false;
    }
    
    // 輸出
    $result = false;
    switch ($mime) {
        case 'image/gif':  $result = imagegif($dst, $dstFile); break;
        case 'image/jpeg': $result = imagejpeg($dst, $dstFile, $quality); break;
        case 'image/png':  $result = imagepng($dst, $dstFile, 9); break;  // 壓縮等級 0-9
        case 'image/webp': $result = imagewebp($dst, $dstFile, $quality); break;
        case 'image/bmp':  $result = imagebmp($dst, $dstFile); break;
    }
    
    imagedestroy($src);
    imagedestroy($dst);
    return $result;
}

使用範例

$source = 'uploads/photo.jpg';
$thumb = 'uploads/thumb_' . basename($source);

$info = getimagesize($source);
if ($info) {
    $maxW = 300; $maxH = 300;
    $ratio = min($maxW/$info[0], $maxH/$info[1]);
    $dstW = (int)round($info[0] * $ratio);
    $dstH = (int)round($info[1] * $ratio);
    
    if (makethumb2($source, $thumb, $dstW, $dstH, 90)) {
        echo "縮圖生成成功: $thumb ({$dstW}x{$dstH})";
    } else {
        echo "縮圖生成失敗";
    }
}

關鍵函數對比

函數品質速度用途
imagecopyresampled()高 (雙三次插值)較慢縮圖、生產環境
imagecopyresized()低 (最近鄰插值)快預覽、即時縮放

永遠使用 imagecopyresampled(),除非極度追求速度且接受鋸齒。

進階功能擴充

1. 智慧裁切 (Crop) - 固定長寬比

function thumbCrop($srcFile, $dstFile, $dstW, $dstH, $quality = 85) {
    $info = getimagesize($srcFile);
    $srcW = $info[0]; $srcH = $info[1];
    
    $srcRatio = $srcW / $srcH;
    $dstRatio = $dstW / $dstH;
    
    if ($srcRatio > $dstRatio) {
        // 來源較寬 → 裁切左右
        $cropW = $srcH * $dstRatio;
        $cropH = $srcH;
        $srcX = ($srcW - $cropW) / 2;
        $srcY = 0;
    } else {
        // 來源較高 → 裁切上下
        $cropW = $srcW;
        $cropH = $srcW / $dstRatio;
        $srcX = 0;
        $srcY = ($srcH - $cropH) / 2;
    }
    
    $src = imagecreatefromjpeg($srcFile); // 簡化
    $dst = imagecreatetruecolor($dstW, $dstH);
    imagecopyresampled($dst, $src, 0, 0, $srcX, $srcY, $dstW, $dstH, $cropW, $cropH);
    imagejpeg($dst, $dstFile, $quality);
    imagedestroy($src); imagedestroy($dst);
}

2. 加浮水印

function addWatermark($dst, $waterFile, $position = 'bottom-right', $opacity = 50) {
    $water = imagecreatefrompng($waterFile);
    $wW = imagesx($water); $wH = imagesy($water);
    $dW = imagesx($dst); $dH = imagesy($dst);
    
    switch ($position) {
        case 'bottom-right': $x = $dW - $wW - 10; $y = $dH - $wH - 10; break;
        case 'center': $x = ($dW - $wW)/2; $y = ($dH - $wH)/2; break;
        // ... 其他位置
    }
    
    imagecopymerge($dst, $water, $x, $y, 0, 0, $wW, $wH, $opacity);
    imagedestroy($water);
}

3. 批次處理目錄

foreach (new DirectoryIterator('photos') as $file) {
    if ($file->isFile() && in_array($file->getExtension(), ['jpg','png'])) {
        makethumb2($file->getPathname(), 'thumbs/'.$file->getBasename(), 200, 200);
    }
}

效能優化建議

  • 啟用 OPcache:PHP 內建 opcode 快取
  • 大量圖片用 Imagine/Intervention Image:封裝 GD/Imagick,API 更友善
  • Imagick 擴展:支援更多格式、多執行緒、向量圖、色彩空間轉換
  • 非同步處理:上傳後丟入隊列,Worker 背景生成縮圖
  • CDN 即時轉檔:Cloudflare Images、Imgix、AWS Lambda@Edge

常見問題

  • 記憶體不足:大圖需大量記憶體 → ini_set('memory_limit', '256M')
  • 執行逾時:set_time_limit(0)
  • 輸出檔案 0 bytes:權限問題、路徑錯誤、磁碟滿
  • 顏色異常:ICC Profile、CMYK 圖片 → Imagick 處理更佳
copyright © 萬盛學電腦網 all rights reserved