萬盛學電腦網

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

PHP GD 圖像裁剪縮放:imagecreatetruecolor 實現不變形填充

需求分析

將任意尺寸源圖縮放/裁剪為固定目標尺寸 (W×H),要求:

  1. 保持原圖長寬比 (不變形)
  2. 目標區域完全填滿 (無留白)
  3. 超出部分居中裁剪

這是典型的「Cover 模式」(CSS object-fit: cover)。

核心算法邏輯

目標比例 = $targetW / $targetH
源比例   = $srcW / $srcH

if (源比例 > 目標比例) {
    // 源圖較寬:按高度縮放,寬度超出 -> 左右裁剪
    $scale = $targetH / $srcH;
    $newW = $srcW * $scale;
    $newH = $targetH;
    $srcX = ($newW - $targetW) / 2 / $scale; // 對應源圖坐標
    $srcY = 0;
    $srcW = $targetW / $scale;
    $srcH = $srcH;
} else {
    // 源圖較高:按寬度縮放,高度超出 -> 上下裁剪
    $scale = $targetW / $srcW;
    $newW = $targetW;
    $newH = $srcH * $scale;
    $srcX = 0;
    $srcY = ($newH - $targetH) / 2 / $scale;
    $srcW = $srcW;
    $srcH = $targetH / $scale;
}

// 1. 創建中間畫布 ($newW x $newH),縮放繪製源圖
// 2. 創建目標畫布 ($targetW x $targetH),從中間畫布裁剪繪製

完整封裝函數 (支援 JPG/PNG/GIF/WebP、保持透明度)

<?php
/**
 * 智能裁剪縮放:Cover 模式 (保持比例、填滿、居中裁剪)
 * @param string $srcPath 源文件路徑
 * @param string $dstPath 目標文件路徑
 * @param int $targetW 目標寬度
 * @param int $targetH 目標高度
 * @param int $quality 輸出質量 0-100 (JPG/WebP)
 * @return bool
 */
function smartResizeCover(string $srcPath, string $dstPath, int $targetW, int $targetH, int $quality = 90): bool {
    if (!file_exists($srcPath)) throw new InvalidArgumentException("源文件不存在: $srcPath");
    if ($targetW <= 0 || $targetH <= 0) throw new InvalidArgumentException('目標尺寸必須大於 0');
    
    // 獲取圖像信息
    [$srcW, $srcH, $type] = getimagesize($srcPath);
    if (!$srcW) throw new RuntimeException('無法識別圖像格式');
    
    // 支援格式映射
    $createFrom = [
        IMAGETYPE_GIF  => 'imagecreatefromgif',
        IMAGETYPE_JPEG => 'imagecreatefromjpeg',
        IMAGETYPE_PNG  => 'imagecreatefrompng',
        IMAGETYPE_WEBP => 'imagecreatefromwebp',
    ];
    $outputFunc = [
        IMAGETYPE_GIF  => 'imagegif',
        IMAGETYPE_JPEG => 'imagejpeg',
        IMAGETYPE_PNG  => 'imagepng',
        IMAGETYPE_WEBP => 'imagewebp',
    ];
    
    if (!isset($createFrom[$type])) throw new RuntimeException('不支援的圖像格式: ' . image_type_to_mime_type($type));
    
    // 載入源圖
    $srcImg = $createFrom[$type]($srcPath);
    if (!$srcImg) throw new RuntimeException('圖像載入失敗');
    
    // 計算縮放與裁剪參數
    $srcRatio = $srcW / $srcH;
    $dstRatio = $targetW / $targetH;
    
    if ($srcRatio > $dstRatio) {
        // 源圖較寬 -> 按高縮放,橫向裁剪
        $scale = $targetH / $srcH;
        $interW = (int)round($srcW * $scale);
        $interH = $targetH;
        $srcX = (int)(($interW - $targetW) / 2 / $scale);
        $srcY = 0;
        $srcWUse = (int)($targetW / $scale);
        $srcHUse = $srcH;
    } else {
        // 源圖較高 -> 按寬縮放,縱向裁剪
        $scale = $targetW / $srcW;
        $interW = $targetW;
        $interH = (int)round($srcH * $scale);
        $srcX = 0;
        $srcY = (int)(($interH - $targetH) / 2 / $scale);
        $srcWUse = $srcW;
        $srcHUse = (int)($targetH / $scale);
    }
    
    // 步驟1: 創建中間畫布並縮放繪製 (高質量重採樣)
    $interImg = imagecreatetruecolor($interW, $interH);
    
    // 保持透明通道 (PNG/GIF/WebP)
    if (in_array($type, [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP])) {
        imagealphablending($interImg, false);
        imagesavealpha($interImg, true);
        $transparent = imagecolorallocatealpha($interImg, 0, 0, 0, 127);
        imagefill($interImg, 0, 0, $transparent);
    }
    
    imagecopyresampled($interImg, $srcImg, 0, 0, 0, 0, $interW, $interH, $srcW, $srcH);
    imagedestroy($srcImg); // 釋放內存
    
    // 步驟2: 創建目標畫布並裁剪
    $dstImg = imagecreatetruecolor($targetW, $targetH);
    
    if (in_array($type, [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP])) {
        imagealphablending($dstImg, false);
        imagesavealpha($dstImg, true);
        $transparent = imagecolorallocatealpha($dstImg, 0, 0, 0, 127);
        imagefill($dstImg, 0, 0, $transparent);
    }
    
    imagecopy($dstImg, $interImg, 0, 0, $srcX, $srcY, $targetW, $targetH);
    imagedestroy($interImg);
    
    // 輸出
    $func = $outputFunc[$type];
    $result = match($type) {
        IMAGETYPE_JPEG => $func($dstImg, $dstPath, $quality),
        IMAGETYPE_PNG  => $func($dstImg, $dstPath, (int)round($quality / 10)), // PNG 壓縮級 0-9
        IMAGETYPE_WEBP => $func($dstImg, $dstPath, $quality),
        default        => $func($dstImg, $dstPath),
    };
    
    imagedestroy($dstImg);
    return $result;
}

// 使用示例
try {
    smartResizeCover('uploads/photo.jpg', 'thumbs/photo_300x200.jpg', 300, 200, 85);
    echo '縮略圖生成成功';
} catch (Exception $e) {
    echo '失敗: ' . $e->getMessage();
}
?>

進階:批量生成多規格縮略圖

<?php
function generateThumbnails(string $srcPath, string $outDir, array $sizes): array {
    $results = [];
    foreach ($sizes as $name => [$w, $h]) {
        $dst = $outDir . '/' . pathinfo($srcPath, PATHINFO_FILENAME) . "_{$name}.webp";
        try {
            smartResizeCover($srcPath, $dst, $w, $h, 80);
            $results[$name] = ['path' => $dst, 'width' => $w, 'height' => $h];
        } catch (Exception $e) {
            $results[$name] = ['error' => $e->getMessage()];
        }
    }
    return $results;
}

// 定義規格
$specs = [
    'thumb'  => [150, 150],
    'small'  => [300, 200],
    'medium' => [600, 400],
    'large'  => [1200, 800],
];

$results = generateThumbnails('uploads/original.jpg', 'public/thumbs', $specs);
print_r($results);
?>

性能優化建議

  • 使用 ImageMagick (imagick 擴展):C 底層實現,速度比 GD 快 3-10 倍,支援更多格式、色彩空間、濾鏡。
  • 異步處理:上傳後推入隊列,Worker 後台生成縮略圖,前端輪詢/WebSocket 通知完成。
  • 緩存衍生圖:按「源文件哈希+尺寸」命名,避免重複生成。
  • 按需生成:首次訪問某尺寸時生成 (Nginx try_files + PHP 落地),而非上傳時全生成。

ImageMagick 版對比 (推薦生產環境)

<?php
function smartResizeCoverImagick(string $src, string $dst, int $w, int $h, int $quality = 85): bool {
    $im = new Imagick($src);
    $im->setImageFormat('webp'); // 統一輸出 WebP
    $im->thumbnailImage($w, $h, true, true); // true=保持比例, true=裁剪填滿 (Cover模式)
    $im->setImageCompressionQuality($quality);
    $im->writeImage($dst);
    $im->destroy();
    return true;
}
?>

總結

GD 库 imagecreatetruecolor + imagecopyresampled + imagecopy 可實現高質量 Cover 模式裁剪。關鍵在於兩步驟:先按長邊縮放至覆蓋目標區域,再居中裁剪。生產環境強烈建議使用 ImageMagick (imagick 擴展) 獲得更好性能、質量與格式支援。

copyright © 萬盛學電腦網 all rights reserved