萬盛學電腦網

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

PHP GD 實作圖片裁剪與縮略圖生成:imagecopyresampled 核心應用

核心函式:imagecopyresampled

bool imagecopyresampled(
    GdImage $dst, GdImage $src,
    int $dstX, int $dstY,      // 目標貼上座標
    int $srcX, int $srcY,      // 來源裁剪起始座標
    int $dstW, int $dstH,      // 目標寬高 (縮放後)
    int $srcW, int $srcH       // 來源裁剪寬高
)

**一次完成「裁剪區域選取」+「縮放/放大」+「貼上目標」**。

案例 1:使用者頭像裁剪 (前端選區 → 後端生成)

前端 (如 Cropper.js、imgAreaSelect) 傳送:`x, y, width, height` (相對原圖座標)。

<?php
function cropAndResize(string $srcPath, int $srcX, int $srcY, int $srcW, int $srcH, int $dstW, int $dstH, string $outputPath): bool
{
    $src = imagecreatefromstring(file_get_contents($srcPath));
    if (!$src) return false;

    $dst = imagecreatetruecolor($dstW, $dstH);

    // 關鍵:來源座標 ($srcX,$srcY) + 來源寬高 ($srcW,$srcH) → 目標 ($dstW,$dstH)
    $ok = imagecopyresampled($dst, $src, 0, 0, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH);

    if ($ok) {
        imagejpeg($dst, $outputPath, 90);
    }
    imagedestroy($src);
    imagedestroy($dst);
    return $ok;
}

// 使用:前端傳 x=100, y=12, w=200, h=200 → 輸出 100x100
cropAndResize('avatar_original.jpg', 100, 12, 200, 200, 100, 100, 'avatar_100.jpg');

案例 2:純縮略圖 (不裁剪、等比縮放)

來源座標 (0,0),來源寬高 = 原圖寬高,目標寬高按比例計算。

function createThumbnail(string $srcPath, int $maxW, int $maxH, string $outputPath): bool
{
    $src = imagecreatefromstring(file_get_contents($srcPath));
    if (!$src) return false;

    $srcW = imagesx($src);
    $srcH = imagesy($src);

    // 計算等比尺寸
    $ratio = min($maxW / $srcW, $maxH / $srcH);
    $dstW = (int)round($srcW * $ratio);
    $dstH = (int)round($srcH * $ratio);

    $dst = imagecreatetruecolor($dstW, $dstH);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);

    imagejpeg($dst, $outputPath, 90);
    imagedestroy($src);
    imagedestroy($dst);
    return true;
}

案例 3:裁剪模式 (Cover) - 覆蓋目標框再置中裁剪

適合封面圖、Hero Banner:圖片**填滿**目標框,超出部分裁掉。

function cropCover(string $srcPath, int $dstW, int $dstH, string $outputPath): bool
{
    $src = imagecreatefromstring(file_get_contents($srcPath));
    if (!$src) return false;

    $srcW = imagesx($src);
    $srcH = imagesy($src);

    $ratioSrc = $srcW / $srcH;
    $ratioDst = $dstW / $dstH;

    if ($ratioSrc > $ratioDst) {
        // 來源較寬 → 以高度為基準縮放,寬度超出再裁剪
        $srcY = 0;
        $srcH2 = $srcH;
        $srcW2 = (int)round($srcH * $ratioDst);
        $srcX = (int)(($srcW - $srcW2) / 2);
    } else {
        // 來源較高 → 以寬度為基準
        $srcX = 0;
        $srcW2 = $srcW;
        $srcH2 = (int)round($srcW / $ratioDst);
        $srcY = (int)(($srcH - $srcH2) / 2);
    }

    $dst = imagecreatetruecolor($dstW, $dstH);
    imagecopyresampled($dst, $src, 0, 0, $srcX, $srcY, $dstW, $dstH, $srcW2, $srcH2);

    imagejpeg($dst, $outputPath, 90);
    imagedestroy($src);
    imagedestroy($dst);
    return true;
}

前端配合:Cropper.js 範例

<!-- HTML -->
<img id="avatar" src="original.jpg" alt="頭像">
<button id="cropBtn">確認裁剪</button>

<script src="cropper.min.js"></script>
<script>
const cropper = new Cropper(document.getElementById('avatar'), {
    aspectRatio: 1,           // 正方形
    viewMode: 1,
    autoCropArea: 1,
    responsive: true,
});

document.getElementById('cropBtn').onclick = () => {
    const data = cropper.getData(true); // {x, y, width, height, rotate, scaleX, scaleY}
    fetch('crop.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(data)
    }).then(r => r.json()).then(res => {
        if (res.success) location.reload();
    });
};
</script>

資源管理與錯誤處理重點

  • **必須 `imagedestroy()`** 釋放 GD 資源,長時間運行腳本 (CLI/Queue Worker) 否則記憶體洩漏。
  • `imagecreatefromstring()` 回傳 `false` 代表來源非有效圖片或格式不支援 (需 GD 編譯支援)。
  • 大圖 (超過 2000px) 記憶體峰值大,建議 `ini_set('memory_limit', '256M')` 或分塊處理。
  • 輸出格式對應:`imagejpeg`、`imagepng`、`imagewebp`、`imagegif`、`imageavif` (PHP 8.1+)。

總結

`imagecopyresampled` 是 GD 圖片處理的瑞士刀:**裁剪座標 (srcX,srcY) + 裁剪尺寸 (srcW,srcH) + 目標尺寸 (dstW,dstH)** 任意組合,涵蓋裁剪、縮略、Cover、Contain (白邊) 所有需求。封裝為三大函式 (`cropAndResize`、`createThumbnail`、`cropCover`) 即可滿足 95% 業務場景。

copyright © 萬盛學電腦網 all rights reserved