圖片處理是 Web 開發常見需求:縮圖、水印、格式轉換、等比縮放。SimpleImage 是一個輕量、零依賴(僅需 GD 擴充)、單檔案的 PHP 類別,專注於「簡單好用」,適合快速整合至專案中。
extension=gd)SimpleImage.php 放入專案(官方來源)| 方法 | 用途 | 回傳值 |
|---|---|---|
load($filename) | 載入圖片(JPG/PNG/GIF) | $this (鏈式呼叫) |
save($filename, $type=IMAGETYPE_JPEG, $quality=75, $perms=null) | 儲存至檔案 | bool |
output($type=IMAGETYPE_JPEG) | 直接輸出至瀏覽器 | void |
resizeToWidth($width) | 指定寬度,等比縮放 | $this |
resizeToHeight($height) | 指定高度,等比縮放 | $this |
resize($width, $height) | 指定寬高(可能變形) | $this |
scale($percent) | 按百分比縮放(50 = 50%) | $this |
getWidth() / getHeight() | 取得目前圖片尺寸 | int |
<?php
require 'SimpleImage.php';
$image = new SimpleImage();
$image->load('uploads/product_original.jpg')
->resizeToWidth(300) // 寬 300px,高度自動等比
->save('uploads/product_thumb_300.jpg', IMAGETYPE_JPEG, 85);
<?php
$image = new SimpleImage();
$image->load('banner_source.png')
->resizeToHeight(200)
->save('banner_200h.png', IMAGETYPE_PNG);
<?php
$image = new SimpleImage();
$image->load('photo.jpg')
->scale(50) // 縮小至 50%
->save('photo_half.jpg');
<?php
// thumbnail.php?src=photo.jpg&w=150
require 'SimpleImage.php';
$src = $_GET['src'] ?? 'default.jpg';
$width = (int)($_GET['w'] ?? 150);
// 安全驗證:防止路徑遍歷
$src = basename($src);
$allowed = ['jpg', 'jpeg', 'png', 'gif'];
$ext = strtolower(pathinfo($src, PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) $src = 'default.jpg';
$image = new SimpleImage();
if ($image->load("uploads/$src")) {
header('Content-Type: image/jpeg');
$image->resizeToWidth($width)->output();
} else {
http_response_code(404);
}
<?php
require 'SimpleImage.php';
function downloadAndResize(string $url, int $targetWidth, string $saveDir): ?string
{
// 1. 下載
$ctx = stream_context_create([
'http' => [
'timeout' => 10,
'header' => 'User-Agent: Mozilla/5.0',
'follow_location' => 1,
'max_redirects' => 3,
],
'ssl' => ['verify_peer' => true, 'verify_peer_name' => true],
]);
$content = @file_get_contents($url, false, $ctx);
if (!$content) return null;
// 2. 寫入暫存檔
$tmpDir = sys_get_temp_dir() . '/simpleimage_' . date('Ymd');
@mkdir($tmpDir, 0755, true);
$tmpFile = tempnam($tmpDir, 'src_');
file_put_contents($tmpFile, $content);
// 3. 處理
$image = new SimpleImage();
if (!$image->load($tmpFile)) {
@unlink($tmpFile);
return null;
}
$image->resizeToWidth($targetWidth);
// 4. 儲存結果
@mkdir($saveDir, 0755, true);
$outFile = $saveDir . '/' . uniqid('img_') . '.jpg';
$image->save($outFile, IMAGETYPE_JPEG, 85);
// 5. 清理暫存
@unlink($tmpFile);
return $outFile;
}
// 使用
$out = downloadAndResize(
'https://example.com/large-photo.jpg',
800,
__DIR__ . '/public/thumbs'
);
echo $out ? "完成: $out" : "失敗";
<?php
class SimpleImage {
private $image;
private $imageType;
public function load($filename) {
$info = getimagesize($filename);
if (!$info) return false;
$this->imageType = $info[2];
switch ($this->imageType) {
case IMAGETYPE_JPEG: $this->image = @imagecreatefromjpeg($filename); break;
case IMAGETYPE_GIF: $this->image = @imagecreatefromgif($filename); break;
case IMAGETYPE_PNG: $this->image = @imagecreatefrompng($filename); break;
default: return false;
}
return $this;
}
public function save($filename, $type = IMAGETYPE_JPEG, $quality = 75, $perms = null) {
$result = false;
switch ($type) {
case IMAGETYPE_JPEG: $result = imagejpeg($this->image, $filename, $quality); break;
case IMAGETYPE_GIF: $result = imagegif($this->image, $filename); break;
case IMAGETYPE_PNG: $result = imagepng($this->image, $filename); break;
}
if ($result && $perms !== null) chmod($filename, $perms);
return $result;
}
public function output($type = IMAGETYPE_JPEG) {
header('Content-Type: ' . image_type_to_mime_type($type));
switch ($type) {
case IMAGETYPE_JPEG: imagejpeg($this->image); break;
case IMAGETYPE_GIF: imagegif($this->image); break;
case IMAGETYPE_PNG: imagepng($this->image); break;
}
}
public function getWidth() { return imagesx($this->image); }
public function getHeight() { return imagesy($this->image); }
public function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getHeight() * $ratio;
return $this->resize($width, $height);
}
public function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
return $this->resize($width, $height);
}
public function scale($percent) {
$width = $this->getWidth() * $percent / 100;
$height = $this->getHeight() * $percent / 100;
return $this->resize($width, $height);
}
public function resize($width, $height) {
$new = imagecreatetruecolor($width, $height);
// 保留 PNG/GIF 透明度
if ($this->imageType == IMAGETYPE_PNG || $this->imageType == IMAGETYPE_GIF) {
imagealphablending($new, false);
imagesavealpha($new, true);
$transparent = imagecolorallocatealpha($new, 255, 255, 255, 127);
imagefill($new, 0, 0, $transparent);
}
imagecopyresampled($new, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new;
return $this;
}
}
75-85 平衡檔案大小與視覺品質;PNG 無損但檔案較大save() 疊加損失ini_set('memory_limit', '256M');極大圖考慮 ImageMagick (imagick 擴充)imagewebp(),可擴充 save() 支援 IMAGETYPE_WEBP| 問題 | 原因 | 解決 |
|---|---|---|
| 輸出圖片空白/破圖 | load() 失敗、路徑錯誤、GD 不支援格式 | 檢查 load() 回傳值、file_exists、getimagesize 回傳 |
| PNG/GIF 透明變黑底 | 未啟用 alpha blending / savealpha | resize() 中加入 alphablending + savealpha 邏輯(上方原始碼已含) |
| 縮放後模糊 | 原圖過小被放大、品質參數過低 | 僅縮小不放大、提高 quality、考慮銳化濾鏡 |
| 記憶體耗盡 | 大尺寸圖片(如 5000x5000)解碼需大量記憶體 | 調高 memory_limit、分塊處理、改用 ImageMagick |
SimpleImage 以 單一檔案、零依賴、API 直覺 三大優勢,成為 PHP 專案快速整合圖片縮放的首選。掌握 load → resizeToWidth/Height/scale → save/output 鏈式操作,即可滿足 90% 的縮圖需求。搭配暫存檔清理、安全驗證、品質調校,即可在生產環境穩定運行。若需更強功能(EXIF 保留、ICC 色彩空間、AVIF/WebP、向量圖),請升級至 Intervention Image 或直接使用 ImageMagick。