App_image_helper 封裝圖片載入、資訊讀取、等比縮放、輸出/儲存功能,支援 JPEG/GIF/PNG/WBMP 格式,提供固定寬度或百分比兩種縮放模式,可選重採樣品質。
<?php
class App_image_helper {
protected $imgFileName;
protected $imgWidth;
protected $imgHeight;
protected $imgMime;
protected $imgResource;
static $imgMineList = [
'jpeg' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'wbmp' => 'image/wbmp',
];
public function __construct($fileName) {
$this->imgFileName = $fileName;
list($this->imgWidth, $this->imgHeight, $this->imgMime) = $this->getImageInfo($fileName);
$this->imgResource = $this->getImageResource($fileName);
}
protected function getImageInfo($fileName) {
if (is_file($fileName)) {
$tmp = getimagesize($fileName);
if ($tmp) return [$tmp[0], $tmp[1], $tmp['mime']];
}
return null;
}
protected function getImageResource($fileName) {
if (!is_file($fileName)) return null;
switch ($this->imgMime) {
case self::$imgMineList['jpeg']: return imagecreatefromjpeg($fileName);
case self::$imgMineList['gif']: return imagecreatefromgif($fileName);
case self::$imgMineList['png']: return imagecreatefrompng($fileName);
case self::$imgMineList['wbmp']: return imagecreatefromwbmp($fileName);
default: return null;
}
}
protected function getSizeByScale($width = 360, $percent = 1) {
if (!$this->imgWidth || !$this->imgHeight) return null;
if ($width) {
return [$width, intval($width * $this->imgHeight / $this->imgWidth)];
} elseif ($percent) {
return [intval($this->imgWidth * $percent), intval($this->imgHeight * $percent)];
}
return null;
}
public function createImage($percentOrWidth = 1, $fileName = null, $quality = 75, $reSample = true) {
$size = $this->getSizeByScale(
($percentOrWidth <= 1) ? null : $percentOrWidth,
($percentOrWidth <= 1) ? $percentOrWidth : null
);
if (!$size) return false;
$thumb = imagecreatetruecolor($size[0], $size[1]);
if ($reSample) {
imagecopyresampled($thumb, $this->imgResource, 0, 0, 0, 0, $size[0], $size[1], $this->imgWidth, $this->imgHeight);
} else {
imagecopyresized($thumb, $this->imgResource, 0, 0, 0, 0, $size[0], $size[1], $this->imgWidth, $this->imgHeight);
}
if ($fileName) {
header('Content-Type: ' . $this->imgMime);
return imagejpeg($thumb, $fileName, $quality);
}
return imagejpeg($thumb, null, $quality); // 直接輸出
}
}
$helper = new App_image_helper('uploads/photo.jpg');
$helper->createImage(300, 'thumbs/photo_300.jpg', 80); // 寬 300px,品質 80
$helper = new App_image_helper('uploads/photo.png');
$helper->createImage(0.5); // 50% 大小,直接輸出圖片二進位
$helper = new App_image_helper('uploads/photo.jpg');
echo "寬: {$helper->imgWidth}, 高: {$helper->imgHeight}, MIME: {$helper->imgMime}";
| 功能 | 函式/參數 | 說明 |
|---|---|---|
| 格式偵測 | getimagesize() | 回傳寬、高、MIME、型態常數 |
| 資源建立 | imagecreatefromjpeg/gif/png/wbmp | 依 MIME 分派對應函式 |
| 高品質縮放 | imagecopyresampled() | 雙三次插值,預設啟用 |
| 快速縮放 | imagecopyresized() | 最近鄰插值,$reSample=false 時啟用 |
| 輸出 JPEG | imagejpeg($res, $file, $quality) | $file=null 直接輸出瀏覽器 |
imagewebp() 輸出 WebP 格式crop() 裁切功能(置中/智慧裁切)