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

PHP 圖片上傳類實例代碼(含縮略圖生成):完整可用版本

     編輯:PHP 相關知識

PHP 圖片上傳類實例代碼(含縮略圖生成):完整可用版本

提供一個可直接複製使用的 Upload 類別,支援檔案驗證、隨機命名、目錄自建、GD 庫等比例縮略圖生成。代碼結構清晰,適合學習參考或直接整合至專案。

一、HTML 表單頁面




    
    圖片上傳測試


    

二、Upload 類別核心代碼 (Upload.php)

fieldName = $fieldName;
        $this->fileInfo = $_FILES[$fieldName] ?? null;
    }

    public function upload() {
        if (!$this->fileInfo) throw new Exception("無檔案上傳");
        $this->checkError()   || throw new Exception($this->errorMsg);
        $this->checkMime()    || throw new Exception($this->errorMsg);
        $this->checkExt()     || throw new Exception($this->errorMsg);
        $this->checkSize()    || throw new Exception($this->errorMsg);
        $this->checkUpload()  || throw new Exception($this->errorMsg);
        $this->ensureDir();
        $this->savePath = $this->uploadDir . '/' . $this->randName() . '.' . $this->ext;
        if (!move_uploaded_file($this->fileInfo['tmp_name'], $this->savePath)) {
            throw new Exception("移動檔案失敗");
        }
        return $this->savePath;
    }

    public function makeThumb($maxW = 100, $maxH = 100) {
        if (!$this->savePath) throw new Exception("請先上傳");
        list($w, $h, $type) = getimagesize($this->savePath);
        $ratio = min($maxW/$w, $maxH/$h);
        $nw = (int)($w*$ratio); $nh = (int)($h*$ratio);
        $thumb = imagecreatetruecolor($nw, $nh);
        $src = $this->createSource($this->savePath, $type);
        imagecopyresampled($thumb, $src, 0,0,0,0, $nw,$nh, $w,$h);
        $out = $this->insertSuffix($this->savePath, '_thumb');
        $this->outputImage($thumb, $out, $type);
        imagedestroy($src); imagedestroy($thumb);
        return $out;
    }

    // 內部方法:checkError, checkMime, checkExt, checkSize, checkUpload, ensureDir, randName, insertSuffix, createSource, outputImage
    // (完整代碼見上一篇「PHP 圖片上傳類實現」一文,此處省略重複)
}

三、處理上傳邏輯 (upload_action.php)

upload();
        $thumb = $uploader->makeThumb(150, 150);
        echo "

上傳成功!

"; echo "

原圖:

"; echo "

縮略圖:

"; } catch (Exception $e) { echo "

錯誤:{$e->getMessage()}

"; } } ?>

四、關鍵功能說明

  • 多重驗證: 錯誤碼、MIME、副檔名、大小、is_uploaded_file 五重防護。
  • 隨機命名: md5(uniqid(microtime(true), true)) 幾乎零碰撞。
  • 等比縮放: 計算寬高比例,使用 imagecopyresampled 高品質重採樣。
  • 透明度支援: PNG/GIF 保持 Alpha 通道(完整版含相關代碼)。

五、擴充建議

  1. 支援多檔上傳(name="files[]" 迴圈處理)。
  2. 整合 Intervention/Image 或 Imagine 庫,支援水印、裁剪、格式轉換。
  3. 上傳後異步推入佇列生成多尺寸縮略圖、WebP 轉換、病毒掃描。
  4. 儲存介面抽象化,支援本地、S3、OSS、雲存儲無縫切換。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved