首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 等比例縮圖函式集:從基礎到進階實作

     編輯:PHP 相關知識

函式一:基礎等比縮放 resize_image()

最簡單的邏輯:取長邊為基準縮放,短邊等比縮小,直接回傳 GD 圖片資源。

<?php
/**
 * 等比縮放並回傳圖片資源
 *
 * @param string $filename 原圖路徑
 * @param string $tmpname  暫存路徑(實際同 $filename)
 * @param int    $xmax     最大寬度
 * @param int    $ymax     最大高度
 * @return resource|false GD 圖片資源
 */
function resize_image(string $filename, string $tmpname, int $xmax, int $ymax) {
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    $im = match ($ext) {
        'jpg', 'jpeg' => imagecreatefromjpeg($tmpname),
        'png' => imagecreatefrompng($tmpname),
        'gif' => imagecreatefromgif($tmpname),
        default => false,
    };
    if (!$im) return false;

    $x = imagesx($im);
    $y = imagesy($im);

    // 原圖已小於限制,直接回傳
    if ($x <= $xmax && $y <= $ymax) return $im;

    // 計算新尺寸
    if ($x >= $y) {
        $newX = $xmax;
        $newY = $newX * $y / $x;
    } else {
        $newY = $ymax;
        $newX = $x / $y * $newY;
    }

    $im2 = imagecreatetruecolor($newX, $newY);
    imagecopyresized($im2, $im, 0, 0, 0, 0, $newX, $newY, $x, $y);
    return $im2;
}
?>

函式二:完整縮圖存檔 creat_thumbnail()

支援 GIF/JPG/PNG 自動偵測、等比縮放、指定輸出路徑與品質。

<?php
/**
 * 產生縮圖並存檔
 *
 * @param string $img   來源圖片路徑
 * @param int    $w     目標最大寬度
 * @param int    $h     目標最大高度
 * @param string $path  輸出資料夾路徑
 * @return string|false 縮圖完整路徑
 */
function creat_thumbnail(string $img, int $w, int $h, string $path) {
    $info = getimagesize($img);
    if (!$info) return false;

    $origX = $info[0];
    $origY = $info[1];
    $origType = $info[2]; // 1=GIF, 2=JPG, 3=PNG

    // 對應建立/輸出函式
    $funcs = [
        1 => ['create' => 'imagecreatefromgif', 'output' => 'imagegif', 'ext' => '.gif'],
        2 => ['create' => 'imagecreatefromjpeg', 'output' => 'imagejpeg', 'ext' => '.jpg'],
        3 => ['create' => 'imagecreatefrompng', 'output' => 'imagepng', 'ext' => '.png'],
    ];
    if (!isset($funcs[$origType])) return false;

    $create = $funcs[$origType]['create'];
    $output = $funcs[$origType]['output'];
    $ext = $funcs[$origType]['ext'];

    $origImage = $create($img);
    if (!$origImage) return false;

    // 等比計算(以 4:3 為基準判斷橫/直)
    if (($origX / $origY) >= (4/3)) {
        $y = round($origY / ($origX / $w));
        $x = $w;
    } else {
        $x = round($origX / ($origY / $h));
        $y = $h;
    }

    $thumb = imagecreatetruecolor($x, $y);
    imagecopyresampled($thumb, $origImage, 0, 0, 0, 0, $x, $y, $origX, $origY);

    $fileName = $path . '/s_' . date('YmdHis') . $ext;
    $result = $output($thumb, $fileName, 80); // 品質 80
    imagedestroy($thumb);
    imagedestroy($origImage);

    return $result ? $fileName : false;
}
?>

進階建議

  • 品質控制:JPEG 輸出時建議品質 80~90;PNG 可用 imagepng($im, $file, 6) 設定壓縮等級。
  • 記憶體管理:大圖處理前調大 memory_limit,處理完立即 imagedestroy()。
  • 錯誤處理:實務上應加入 try-catch、日誌記錄、檔案權限檢查。
  • 現代替代方案:Composer 安裝 intervention/image,一行程式碼搞定縮圖、水印、濾鏡,且支援 Laravel 整合。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved