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

PHP 圖片處理類 ImageCls:上傳、縮略、水印、多規格生成完整封裝

     編輯:PHP 綜合知識

類功能總覽

  • 文件上傳驗證(類型、大小、圖片完整性)
  • 自動保存原圖、生成多規格縮略圖
  • 支援等比縮放、固定尺寸裁剪、居中裁剪
  • 圖片水印(文字/圖片、九宮格位置、透明度)
  • GIF 動圖水印幀級處理
  • 獲取圖片信息(寬高、類型、MIME)

核心類結構

class ImageCls {
    public $file = [];      // 文件信息
    public $dir = '';       // 保存目錄
    public $error_code = 0; // 錯誤碼
    public $max_size = -1;  // 最大 KB

    public function init(array $file, string $dir = 'temp'): bool { ... }
    public function save(): bool { ... }
    public function error(): int { ... }

    // 縮略圖核心
    public function thumb(
        string $image,
        int $maxWidth = 200,
        int $maxHeight = 50,
        int $gen = 0,           // 0=等比, 1=裁剪
        bool $interlace = true,
        string $filepath = '',
        bool $is_preview = true
    ): array|false { ... }

    // 內部縮略邏輯
    private function make_thumb(...): resource { ... }

    // 水印
    public function water(
        string $source,
        string $water,
        int $alpha = 80,
        string $position = '0'  // 0-5: 左上/右上/左下/右下/居中/左上(默認)
    ): bool { ... }

    // 工具方法
    private function fileExt(string $name): string { ... }
    private function isImageExt(string $ext): int { ... }
    private function getImageInfo(string $path): array|false { ... }
    private function isUploadFile(string $source): bool { ... }
    private function getTargetDir(string $dir): string { ... }
    private function saveFile(string $source, string $target): bool { ... }
}

規格圖生成封裝

function get_spec_image(string $img_path, int $width = 0, int $height = 0, int $gen = 0, bool $is_preview = true): string {
    if ($width === 0) return $img_path;

    $info = pathinfo($img_path);
    $base = $info['dirname'] . '/' . $info['filename'];
    $ext = $info['extension'];
    $suffix = $is_preview ? "_{$width}x{$height}" : "o_{$width}x{$height}";
    $new_path = "{$base}{$suffix}.jpg";

    if (!file_exists($new_path)) {
        require_once 'ImageCls.php';
        $img = new ImageCls();
        $img->thumb($img_path, $width, $height, $gen, true, '', $is_preview);
    }
    return $new_path;
}

// 使用:生成三規格
$small  = get_spec_image($data['image'], 48, 48, 0);
$medium = get_spec_image($data['image'], 120, 120, 0);
$large  = get_spec_image($data['image'], 200, 200, 0);

關鍵參數對照

參數含義
$gen = 0等比縮放,長邊貼合限制,短邊留白(不裁剪)
$gen = 1固定尺寸裁剪,居中裁剪填滿
$interlace漸進式 JPEG,網頁加載體驗更好
$position (water)0=左上, 1=右上, 2=左下, 3=右下, 4=居中, 5=左上(默認)
$alpha (water)水印透明度 0-100

GIF 動圖水印處理

類內部引入 GIFReader + GIFEncoder(需額外庫),逐幀合成水印後重新編碼,保持動畫幀延遲。

使用建議

  • 上傳入口統一調用 init() -> save(),失敗即返回錯誤碼
  • 規格圖按需生成(首次訪問觸發),避免上傳時阻塞
  • 水印圖建議預處理為 PNG 透明背景,位置用右下/居中
  • 生產環境建議遷移至 Intervention Image 或 Imagine 庫,支援更多格式、鏈式調用、單元測試友好
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved