萬盛學電腦網

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

PHP 智慧型圖片縮放函數:支援 PNG 透明背景、GIF、JPEG

PHP 智慧型圖片縮放函數:完美保留 PNG 透明背景、支援 GIF/JPEG

功能完整的 smart_resize_image() 函數,支援等比/強制縮放、多格式輸入輸出、透明度保留 (PNG/GIF)、可選覆蓋原檔或回傳資源/瀏覽器輸出。採用 GD 庫 imagecopyresampled 高品質重採樣。

完整函數程式碼 (含詳細註解)

<?php
/**
 * 智慧型圖片縮放
 * @param string $file          來源圖片路徑
 * @param int    $width         目標寬度 (0=按比例)
 * @param int    $height        目標高度 (0=按比例)
 * @param bool   $proportional  true=等比縮放(預設), false=強制拉伸
 * @param string $output        'file'=覆蓋原檔, 'browser'=直接輸出, 'return'=回傳 GD 資源
 * @param bool   $deleteOriginal 覆蓋模式下是否刪除原檔 (預設 true)
 * @param bool   $useLinuxCmd   刪除原檔時是否用 exec(rm) (預設 false)
 * @return bool|resource 成功 true/資源,失敗 false
 */
function smart_resize_image(
    string $file,
    int $width = 0,
    int $height = 0,
    bool $proportional = false,
    string $output = 'file',
    bool $deleteOriginal = true,
    bool $useLinuxCmd = false
) {
    // 1. 參數檢查
    if ($height <= 0 && $width <= 0) return false;

    // 2. 取得原圖資訊
    $info = @getimagesize($file);
    if (!$info) return false;
    [$srcW, $srcH, $type] = $info;

    // 3. 計算目標尺寸
    if ($proportional) {
        if ($width == 0) $factor = $height / $srcH;
        elseif ($height == 0) $factor = $width / $srcW;
        else $factor = min($width / $srcW, $height / $srcH);
        $dstW = (int)round($srcW * $factor);
        $dstH = (int)round($srcH * $factor);
    } else {
        $dstW = ($width <= 0) ? $srcW : $width;
        $dstH = ($height <= 0) ? $srcH : $height;
    }

    // 4. 依格式建立來源資源
    $src = match ($type) {
        IMAGETYPE_GIF  => imagecreatefromgif($file),
        IMAGETYPE_JPEG => imagecreatefromjpeg($file),
        IMAGETYPE_PNG  => imagecreatefrompng($file),
        default => null,
    };
    if (!$src) return false;

    // 5. 建立目標真彩色畫布
    $dst = imagecreatetruecolor($dstW, $dstH);

    // 6. 透明度處理 (關鍵:GIF/PNG)
    if ($type === IMAGETYPE_GIF || $type === IMAGETYPE_PNG) {
        // 找原圖透明色索引
        $trnprtIdx = imagecolortransparent($src);
        if ($trnprtIdx >= 0) {
            // 取得原透明色 RGB
            $trnprtColor = imagecolorsforindex($src, $trnprtIdx);
            // 在新圖分配相同顏色
            $newTrnprtIdx = imagecolorallocate($dst, $trnprtColor['red'], $trnprtColor['green'], $trnprtColor['blue']);
            // 填滿背景並設為透明
            imagefill($dst, 0, 0, $newTrnprtIdx);
            imagecolortransparent($dst, $newTrnprtIdx);
        } elseif ($type === IMAGETYPE_PNG) {
            // PNG 無透明色索引時,建立全透明 alpha 通道
            imagealphablending($dst, false);
            $transparent = imagecolorallocatealpha($dst, 0, 0, 0, 127); // 完全透明
            imagefill($dst, 0, 0, $transparent);
            imagesavealpha($dst, true); // 關鍵:保存 alpha 通道
        }
    }

    // 7. 高品質重採樣縮放
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
    imagedestroy($src); // 釋放來源

    // 8. 刪除原檔 (可選)
    if ($deleteOriginal && $output === 'file') {
        if ($useLinuxCmd) {
            @exec('rm ' . escapeshellarg($file));
        } else {
            @unlink($file);
        }
    }

    // 9. 輸出處理
    switch (strtolower($output)) {
        case 'browser':
            header('Content-Type: ' . image_type_to_mime_type($type));
            $output = null; // 輸出到瀏覽器
            break;
        case 'file':
            $output = $file; // 覆蓋原檔
            break;
        case 'return':
            return $dst; // 回傳 GD 資源供後續處理
        default:
            return false;
    }

    // 10. 依原格式儲存
    $saved = match ($type) {
        IMAGETYPE_GIF  => imagegif($dst, $output),
        IMAGETYPE_JPEG => imagejpeg($dst, $output, 90), // 品質 90
        IMAGETYPE_PNG  => imagepng($dst, $output, 9),   // 壓縮等級 9
        default => false,
    };

    imagedestroy($dst);
    return $saved;
}
?>

使用範例

<?php
// 等比縮放寬度 800px,高度自適應,覆蓋原檔
smart_resize_image('uploads/photo.png', 800, 0, true);

// 強制縮放 200x200 縮圖,輸出到瀏覽器
smart_resize_image('uploads/avatar.jpg', 200, 200, false, 'browser');

// 等比縮放至 300x300 內,回傳 GD 資源再加水印
$thumb = smart_resize_image('uploads/logo.gif', 300, 300, true, 'return');
if ($thumb) {
    // ... 加水印邏輯 ...
    imagepng($thumb, 'final.png');
    imagedestroy($thumb);
}
?>

透明度處理核心邏輯圖解

PNG/GIF 來源圖
       │
       ├─ 有透明色索引 (imagecolortransparent >= 0)
       │     → 取得 RGB → 新圖 allocate 同色 → fill 背景 → 設為透明色
       │
       └─ PNG 無透明色索引 (純 alpha 通道)
             → imagealphablending(false)
             → allocatealpha(0,0,0,127) 全透明色
             → fill 背景
             → imagesavealpha(true)  <-- 關鍵!保存 alpha 通道

常見問題與解決

  • 縮圖變黑/背景變黑:漏做 imagesavealpha(true) 或未關閉 blending。
  • GIF 動畫只剩第一幀:GD 不支援多幀 GIF 處理,需用 Imagick (Imagick::coalesceImages + resize + save)。
  • 記憶體不足:大圖 (如 4000x3000) 需 ~48MB 記憶體,調大 memory_limit 或分塊處理。
  • JPEG 品質:imagejpeg($dst, $file, 85) 85~90 為佳平衡點。

現代替代:Imagick (ImageMagick PHP 擴充)

<?php
$imagick = new Imagick('source.png');
$imagick->thumbnailImage(800, 0, true, true); // 等比、最佳化
$imagick->setImageFormat('png');
$imagick->writeImage('thumb.png');
// 自動處理透明度、ICC 色彩空間、EXIF 方向、多幀 GIF、更高品質濾鏡
?>

建議:生產環境有條件請安裝 php-imagick,功能更強、色彩更準、效能更好。

copyright © 萬盛學電腦網 all rights reserved