萬盛學電腦網

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

PHP 圖片縮略圖生成類完整實作與用法詳解

類別設計目標

App_image_helper 封裝圖片載入、資訊讀取、等比縮放、輸出/儲存功能,支援 JPEG/GIF/PNG/WBMP 格式,提供固定寬度或百分比兩種縮放模式,可選重採樣品質。

完整類別程式碼

<?php
class App_image_helper {
    protected $imgFileName;
    protected $imgWidth;
    protected $imgHeight;
    protected $imgMime;
    protected $imgResource;

    static $imgMineList = [
        'jpeg' => 'image/jpeg',
        'gif'  => 'image/gif',
        'png'  => 'image/png',
        'wbmp' => 'image/wbmp',
    ];

    public function __construct($fileName) {
        $this->imgFileName = $fileName;
        list($this->imgWidth, $this->imgHeight, $this->imgMime) = $this->getImageInfo($fileName);
        $this->imgResource = $this->getImageResource($fileName);
    }

    protected function getImageInfo($fileName) {
        if (is_file($fileName)) {
            $tmp = getimagesize($fileName);
            if ($tmp) return [$tmp[0], $tmp[1], $tmp['mime']];
        }
        return null;
    }

    protected function getImageResource($fileName) {
        if (!is_file($fileName)) return null;
        switch ($this->imgMime) {
            case self::$imgMineList['jpeg']: return imagecreatefromjpeg($fileName);
            case self::$imgMineList['gif']:  return imagecreatefromgif($fileName);
            case self::$imgMineList['png']:  return imagecreatefrompng($fileName);
            case self::$imgMineList['wbmp']: return imagecreatefromwbmp($fileName);
            default: return null;
        }
    }

    protected function getSizeByScale($width = 360, $percent = 1) {
        if (!$this->imgWidth || !$this->imgHeight) return null;
        if ($width) {
            return [$width, intval($width * $this->imgHeight / $this->imgWidth)];
        } elseif ($percent) {
            return [intval($this->imgWidth * $percent), intval($this->imgHeight * $percent)];
        }
        return null;
    }

    public function createImage($percentOrWidth = 1, $fileName = null, $quality = 75, $reSample = true) {
        $size = $this->getSizeByScale(
            ($percentOrWidth <= 1) ? null : $percentOrWidth,
            ($percentOrWidth <= 1) ? $percentOrWidth : null
        );
        if (!$size) return false;

        $thumb = imagecreatetruecolor($size[0], $size[1]);
        if ($reSample) {
            imagecopyresampled($thumb, $this->imgResource, 0, 0, 0, 0, $size[0], $size[1], $this->imgWidth, $this->imgHeight);
        } else {
            imagecopyresized($thumb, $this->imgResource, 0, 0, 0, 0, $size[0], $size[1], $this->imgWidth, $this->imgHeight);
        }

        if ($fileName) {
            header('Content-Type: ' . $this->imgMime);
            return imagejpeg($thumb, $fileName, $quality);
        }
        return imagejpeg($thumb, null, $quality); // 直接輸出
    }
}

使用範例

1. 固定寬度縮放並儲存

$helper = new App_image_helper('uploads/photo.jpg');
$helper->createImage(300, 'thumbs/photo_300.jpg', 80); // 寬 300px,品質 80

2. 百分比縮放並直接輸出瀏覽器

$helper = new App_image_helper('uploads/photo.png');
$helper->createImage(0.5); // 50% 大小,直接輸出圖片二進位

3. 取得圖片資訊

$helper = new App_image_helper('uploads/photo.jpg');
echo "寬: {$helper->imgWidth}, 高: {$helper->imgHeight}, MIME: {$helper->imgMime}";

關鍵技術點

功能函式/參數說明
格式偵測getimagesize()回傳寬、高、MIME、型態常數
資源建立imagecreatefromjpeg/gif/png/wbmp依 MIME 分派對應函式
高品質縮放imagecopyresampled()雙三次插值,預設啟用
快速縮放imagecopyresized()最近鄰插值,$reSample=false 時啟用
輸出 JPEGimagejpeg($res, $file, $quality)$file=null 直接輸出瀏覽器

擴展建議

  • 支援 imagewebp() 輸出 WebP 格式
  • 新增 crop() 裁切功能(置中/智慧裁切)
  • 加入水印功能(文字/圖片水印)
  • 實作快取機制避免重複生成
  • 例外處理:檔案不存在、格式不支援、記憶體不足
copyright © 萬盛學電腦網 all rights reserved