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

PHP 利用 GD 庫生成縮略圖完整代碼實現(支援 JPG、GIF、PNG 格式)

     編輯:PHP 相關知識

在 PHP 開發中,圖片縮略圖生成是常見需求。本文提供一個基於 GD 庫的完整類別,支援 JPG、GIF、PNG 三種主流格式,並包含錯誤處理與比例縮放邏輯,可直接整合到專案中使用。

核心類別:ImageResize

該類別封裝了從檢測 GD 環境、讀取原圖資訊、計算目標尺寸、重新採樣到輸出檔案的完整流程。使用方式極簡單:

<?php
$newImage = new ImageResize();
$newImage->resize("source.jpg", "thumb.jpg", 1000, 1000);
echo $newImage->GetLastError();

關鍵方法解析

1. 環境檢測 _checkenv()

啟動時自動檢查 gd_info 函數是否存在,確保伺服器已安裝並啟用 GD 擴展。

2. 圖片資源建立 _create()

根據 getimagesize() 回傳的類型代碼(1=GIF, 2=JPG, 3=PNG),呼叫對應的 imagecreatefrom* 函數建立圖片資源。

3. 尺寸計算 _dstsize()

依原圖寬高比與目標框寬高比,等比縮放,確保縮略圖不變形。邏輯為:若原圖較扁,以高度為基準計算寬度;否則以寬度為基準計算高度。

4. 重新採樣與輸出 _resize()

  • 建立真彩色畫布 imagecreatetruecolor,並填充透明背景(imagecolorallocatealpha)。
  • 使用 imagecopyresampled 高質量重新採樣。
  • 依序嘗試 imagejpeg、imagepng、imagegif 輸出,相容不同格式需求。

錯誤處理機制

類別內部維護 $error 陣列,提供 GetLastError() 與 GetAllError() 兩種獲取方式,方便除錯與日誌記錄。

完整代碼

<?php
class ImageResize {
    private $localimage;
    private $remoteimage;
    private $localinfo;
    private $error = [];

    public function resize($localimg, $remoteimg, $x, $y) {
        if (!$this->_checkenv()) return false;
        $this->localimage = $localimg;
        $this->remoteimage = $remoteimg;
        $this->localinfo = getimagesize($this->localimage);
        return $this->_resize($x, $y);
    }

    private function _checkenv() {
        if (!function_exists('gd_info')) {
            $this->error[] = "當前環境不支援 GD 圖像處理,請先安裝 GD 庫並開啟 PHP 相關擴展";
            return false;
        }
        return true;
    }

    private function _resize($x, $y) {
        if (!$this->localinfo) {
            $this->error[] = "本地圖像文件不存在";
            return false;
        }
        $im = @$this->_create($this->localinfo[2]);
        if (!$im) {
            $this->error[] = "當前 GD 庫不支援圖像類型:{$this->localinfo['mime']}";
            return false;
        }
        $dstsize = $this->_dstsize($x, $y);
        $dstim = @imagecreatetruecolor($dstsize["width"], $dstsize["height"]);
        $whitecolor = @imagecolorallocatealpha($dstim, 0, 0, 0, 127);
        imagefill($dstim, 0, 0, $whitecolor);
        $re = @imagecopyresampled($dstim, $im, 0, 0, 0, 0, $dstsize["width"], $dstsize["height"], $this->localinfo[0], $this->localinfo[1]);
        if (!$re) {
            $this->error[] = "圖像重新採樣失敗";
            return false;
        }
        // 依序嘗試三種格式輸出
        if (!imagejpeg($dstim, $this->remoteimage)
            && !imagepng($dstim, $this->remoteimage)
            && !imagegif($dstim, $this->remoteimage)) {
            $this->error[] = "保存縮略圖到 {$this->remoteimage} 失敗,請檢查 GD 環境及目錄寫入權限。";
            return false;
        }
        $this->error[] = "success";
        return true;
    }

    private function _create($code) {
        $src = $this->localimage;
        switch ($code) {
            case 1: return imagecreatefromgif($src);
            case 2: return imagecreatefromjpeg($src);
            case 3: return imagecreatefrompng($src);
            default: return false;
        }
    }

    private function _dstsize($x, $y) {
        list($srcwidth, $srcheight) = $this->localinfo;
        if (($srcwidth / $srcheight) < ($x / $y)) {
            $x = floor($y * $srcwidth / $srcheight);
        } else {
            $y = floor($x * $srcheight / $srcwidth);
        }
        return ["width" => $x, "height" => $y];
    }

    public function GetLastError() { return array_pop($this->error); }
    public function GetAllError() { return $this->error; }
}

將上述代碼存為 ImageResize.class.php 即可在專案中直接引入使用。若需調整輸出品質,可在 imagejpeg 呼叫時加入第三參數(0-100)。

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