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

PHP 等比縮放生成縮略圖函數:保持比例不變形的完整實現

     編輯:PHP 相關知識

PHP 生成等比縮略圖:核心算法與完整代碼實現

上傳圖片後生成縮略圖是常見需求,關鍵在於「等比縮放」——保持寬高比,在指定最大尺寸框內完整顯示。本文提供生產級可用函數。

核心算法邏輯

  1. 獲取原圖尺寸 getimagesize()
  2. 計算縮放比例:min($maxWidth/$width, $maxHeight/$height)
  3. 若比例 < 1 則需縮放,否則保持原圖
  4. 創建真彩色畫布 imagecreatetruecolor()
  5. 高質量重採樣 imagecopyresampled()
  6. 按原格式輸出 imagejpeg/png/gif()

完整函數代碼

<?php
/**
 * 等比縮放生成縮略圖
 * @param string $srcImage 源圖片路徑
 * @param string $toFile 目標文件路徑(不含擴展名)
 * @param int $maxWidth 最大寬度
 * @param int $maxHeight 最大高度
 * @param int $quality 圖片質量 1-100
 * @return string|false 成功返回文件名,失敗返回 false
 */
function resizeImage($srcImage, $toFile, $maxWidth = 100, $maxHeight = 100, $quality = 90) {
    if (!file_exists($srcImage)) return false;
    
    list($width, $height, $type) = getimagesize($srcImage);
    if ($width <= $maxWidth && $height <= $maxHeight) return false; // 無需縮放
    
    // 計算縮放比例
    $scale = min($maxWidth / $width, $maxHeight / $height);
    $newWidth = (int)($width * $scale);
    $newHeight = (int)($height * $scale);
    
    // 載入源圖
    switch ($type) {
        case IMAGETYPE_GIF:  $src = imagecreatefromgif($srcImage);  break;
        case IMAGETYPE_JPEG: $src = imagecreatefromjpeg($srcImage); break;
        case IMAGETYPE_PNG:  $src = imagecreatefrompng($srcImage);  break;
        default: return false;
    }
    
    // 創建目標畫布
    $dst = imagecreatetruecolor($newWidth, $newHeight);
    
    // PNG/GIF 保持透明度
    if ($type === IMAGETYPE_PNG || $type === IMAGETYPE_GIF) {
        imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
        imagealphablending($dst, false);
        imagesavealpha($dst, true);
    }
    
    // 高質量重採樣
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    
    // 輸出文件
    $ext = ['', 'gif', 'jpg', 'png'][$type];
    $targetFile = $toFile . '.' . $ext;
    $result = false;
    
    switch ($type) {
        case IMAGETYPE_GIF:  $result = imagegif($dst, $targetFile); break;
        case IMAGETYPE_JPEG: $result = imagejpeg($dst, $targetFile, $quality); break;
        case IMAGETYPE_PNG:  $result = imagepng($dst, $targetFile, (int)($quality/10)); break;
    }
    
    // 清理資源
    imagedestroy($src);
    imagedestroy($dst);
    
    return $result ? basename($targetFile) : false;
}

使用示例

$thumb = resizeImage(
    'uploads/photo.jpg',  // 源文件
    'thumbs/photo',       // 目標路徑(不含擴展名)
    300, 200,             // 最大 300x200
    85                    // JPEG 質量 85%
);
if ($thumb) {
    echo "縮略圖生成成功:$thumb";
}

進階擴展建議

  • 支持 scale_fill 模式:縮放填滿並居中,空白處填充背景色
  • 支持 crop 模式:智能裁剪居中區域(適合頭像)
  • 添加水印合成功能
  • 集成 Imagick 獲得更好性能與格式支持
  • 添加緩存機制避免重複生成

常見問題

  1. 內存不足:大圖處理需調大 memory_limit 或分塊處理
  2. 透明度丟失:PNG/GIF 必須設置 imagesavealpha 和 imagealphablending
  3. 質量參數:JPEG 1-100,PNG 0-9(壓縮級別,非質量)
  4. 權限問題:目標目錄需 Web 服務器用戶寫入權限

這個函數經過實戰驗證,代碼簡潔、邏輯清晰,可直接集成到項目中使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved