類別設計目標
- 統一上傳入口:驗證、搬移、資訊提取
- 支援 GD 建立縮圖、裁剪、水印
- 多規格輸出:原圖、縮圖、中圖、大圖、WebP 轉換
- 錯誤碼標準化、鏈式調用、可擴充
核心類別結構
<?php
class ImageProcessor {
private array $file = [];
private string $saveDir = 'uploads/';
private int $maxSize = 5 * 1024 * 1024; // 5MB
private array $allowedExt = ['jpg','jpeg','png','gif','webp'];
private int $errorCode = 0;
public function __construct(array $options = []) {
foreach ($options as $k => $v) {
if (property_exists($this, $k)) $this->$k = $v;
}
}
/** 處理 $_FILES 上傳 */
public function handleUpload(array $file): bool {
if (!$this->validateUpload($file)) return false;
$this->file = $file;
$this->preparePaths();
return $this->moveFile();
}
/** 從現有檔案初始化 */
public function load(string $path): bool {
if (!file_exists($path) || !is_readable($path)) {
$this->errorCode = -1;
return false;
}
$this->file['local_path'] = $path;
$this->file['image_info'] = $this->getImageInfo($path);
return $this->file['image_info'] !== false;
}
private function validateUpload(array $file): bool {
if ($file['error'] !== UPLOAD_ERR_OK) {
$this->errorCode = $file['error'];
return false;
}
if ($file['size'] > $this->maxSize) {
$this->errorCode = -2; // 檔案過大
return false;
}
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $this->allowedExt, true)) {
$this->errorCode = -3; // 副檔名不允許
return false;
}
// MIME 再驗證
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (!str_starts_with($mime, 'image/')) {
$this->errorCode = -4; // 非圖片
return false;
}
return true;
}
private function preparePaths(): void {
$ext = 'jpg'; // 統一轉 JPG 或保留原副檔名
$name = md5(uniqid('', true)) . '.' . $ext;
$dateDir = date('Y/m/d');
$fullDir = $this->saveDir . $dateDir;
if (!is_dir($fullDir)) mkdir($fullDir, 0755, true);
$this->file['save_dir'] = $fullDir;
$this->file['save_name'] = $name;
$this->file['save_path'] = $fullDir . '/' . $name;
$this->file['url_path'] = '/' . $fullDir . '/' . $name;
}
private function moveFile(): bool {
if (move_uploaded_file($this->file['tmp_name'], $this->file['save_path'])) {
$this->file['image_info'] = $this->getImageInfo($this->file['save_path']);
return $this->file['image_info'] !== false;
}
$this->errorCode = -5;
return false;
}
public function getImageInfo(string $path): ?array {
$info = @getimagesize($path);
if (!$info) return null;
return [
'width' => $info[0],
'height' => $info[1],
'type' => $info[2], // IMAGETYPE_*
'mime' => $info['mime'],
];
}
/** 生成縮圖
* @param int $maxW 最大寬
* @param int $maxH 最大高
* @param int $mode 1=等比縮放 2=裁剪填滿 3=固定寬高拉伸
* @param string $suffix 檔名後綴
* @return bool
*/
public function thumb(int $maxW, int $maxH, int $mode = 1, string $suffix = '_thumb'): bool {
if (empty($this->file['save_path']) || !$this->file['image_info']) return false;
$src = $this->file['save_path'];
$info = $this->file['image_info'];
$srcW = $info['width']; $srcH = $info['height'];
// 計算目標尺寸
switch ($mode) {
case 1: // 等比縮放
$scale = min($maxW/$srcW, $maxH/$srcH);
$dstW = (int)($srcW * $scale);
$dstH = (int)($srcH * $scale);
$srcX = $srcY = 0;
$srcCropW = $srcW; $srcCropH = $srcH;
break;
case 2: // 裁剪填滿 (置中裁剪)
$scale = max($maxW/$srcW, $maxH/$srcH);
$cropW = (int)($maxW / $scale);
$cropH = (int)($maxH / $scale);
$srcX = (int)(($srcW - $cropW) / 2);
$srcY = (int)(($srcH - $cropH) / 2);
$srcCropW = $cropW; $srcCropH = $cropH;
$dstW = $maxW; $dstH = $maxH;
break;
case 3: // 拉伸
$dstW = $maxW; $dstH = $maxH;
$srcX = $srcY = 0;
$srcCropW = $srcW; $srcCropH = $srcH;
break;
default: return false;
}
$srcImg = $this->createFromType($src, $info['type']);
if (!$srcImg) return false;
$dstImg = imagecreatetruecolor($dstW, $dstH);
// 保持透明度 (PNG/GIF/WebP)
if (in_array($info['type'], [IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP])) {
imagealphablending($dstImg, false);
imagesavealpha($dstImg, true);
$transparent = imagecolorallocatealpha($dstImg, 0,0,0,127);
imagefill($dstImg, 0, 0, $transparent);
}
imagecopyresampled($dstImg, $srcImg, 0, 0, $srcX, $srcY, $dstW, $dstH, $srcCropW, $srcCropH);
imagedestroy($srcImg);
// 可選:加水印
// $this->watermark($dstImg);
$pathInfo = pathinfo($this->file['save_path']);
$thumbPath = $pathInfo['dirname'] . '/' . $pathInfo['filename'] . $suffix . '.jpg';
$result = imagejpeg($dstImg, $thumbPath, 85);
imagedestroy($dstImg);
if ($result) {
$this->file['thumbs'][$suffix] = [
'path' => $thumbPath,
'url' => str_replace('\\', '/', $thumbPath),
'width' => $dstW,
'height' => $dstH,
];
return true;
}
return false;
}
private function createFromType(string $path, int $type): ?resource {
return match($type) {
IMAGETYPE_JPEG => imagecreatefromjpeg($path),
IMAGETYPE_PNG => imagecreatefrompng($path),
IMAGETYPE_GIF => imagecreatefromgif($path),
IMAGETYPE_WEBP => function_exists('imagecreatefromwebp') ? imagecreatefromwebp($path) : null,
default => null,
};
}
public function getError(): int { return $this->errorCode; }
public function getFileInfo(): array { return $this->file; }
}
使用範例
<?php
$processor = new ImageProcessor([
'saveDir' => 'storage/images/',
'maxSize' => 10 * 1024 * 1024,
]);
// 上傳處理
if ($processor->handleUpload($_FILES['avatar'])) {
$info = $processor->getFileInfo();
echo "原圖: {$info['url_path']}\n";
// 生成多規格
$processor->thumb(100, 100, 2, '_avatar'); // 100x100 裁剪
$processor->thumb(300, 300, 1, '_medium'); // 300x300 等比
$processor->thumb(800, 600, 1, '_large'); // 800x600 等比
print_r($info['thumbs']);
} else {
echo "上傳失敗,錯誤碼: " . $processor->getError();
}
// 或載入現有圖片生成縮圖
$processor2 = new ImageProcessor();
$processor2->load('storage/images/2024/01/abc.jpg');
$processor2->thumb(200, 200, 2, '_thumb');
進階功能擴充
- 水印:
imagecopy() 疊加 Logo/文字,支援透明度、位置 (九宮格)
- WebP/AVIF 轉換:
imagewebp()、imageavif() (PHP 8.1+)
- 圖片優化:
jpegoptim、optipng、cwebp 呼叫外部工具
- 儲存驅動抽象:本地、S3、OSS、FTP 統一介面
- 非同步處理:上傳後推入隊列 (Redis/RabbitMQ),Worker 處理縮圖
效能建議
- 大圖處理設定
ini_set('memory_limit', '256M')
- 使用
imagecopyresampled 而非 imagecopyresized (品質更好)
- 批次處理時重複利用 GD 資源,避免頻繁建立/銷毀
- 考慮 ImageMagick (Imagick):功能更全、多執行緒、支援更多格式