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 |
類內部引入 GIFReader + GIFEncoder(需額外庫),逐幀合成水印後重新編碼,保持動畫幀延遲。
init() -> save(),失敗即返回錯誤碼