App 發布需要多種尺寸圖標(iOS 1024x1024、Android 192x192、各類啟動圖等)。設計師通常只提供最大尺寸源圖,開發者需自動裁剪縮放生成全套規格。本文提供基於 PHP GD 的完整類別實現,支援縮放、裁剪、水印、多格式輸出、批量打包下載。
<?php
declare(strict_types=1);
class ImageProcessor {
private $sourcePath;
private $sourceInfo; // ['width', 'height', 'type', 'mime']
private $image; // GD 資源
private $errors = [];
// App 圖標標準尺寸規範 (寬, 高, 文件名後綴)
public const ICON_SPECS = [
// iOS
'ios_1024' => [1024, 1024, 'Icon-1024.png'],
'ios_180' => [180, 180, 'Icon-60@3x.png'],
'ios_120' => [120, 120, 'Icon-60@2x.png'],
'ios_87' => [87, 87, 'Icon-29@3x.png'],
'ios_58' => [58, 58, 'Icon-29@2x.png'],
'ios_80' => [80, 80, 'Icon-40@2x.png'],
'ios_60' => [60, 60, 'Icon-60.png'],
'ios_57' => [57, 57, 'Icon-57.png'], // iOS 7- legacy
'ios_40' => [40, 40, 'Icon-40.png'],
'ios_29' => [29, 29, 'Icon-29.png'],
// Android (mipmap)
'android_192' => [192, 192, 'ic_launcher.png'],
'android_144' => [144, 144, 'ic_launcher_xxxhdpi.png'],
'android_96' => [96, 96, 'ic_launcher_xxhdpi.png'],
'android_72' => [72, 72, 'ic_launcher_xhdpi.png'],
'android_48' => [48, 48, 'ic_launcher_hdpi.png'],
'android_36' => [36, 36, 'ic_launcher_mdpi.png'],
// Web / PWA
'web_512' => [512, 512, 'icon-512.png'],
'web_192' => [192, 192, 'icon-192.png'],
// 通用
'favicon_32' => [32, 32, 'favicon-32.png'],
'favicon_16' => [16, 16, 'favicon-16.png'],
];
public function __construct(string $sourcePath) {
$this->sourcePath = $sourcePath;
$this->loadSource();
}
private function loadSource(): void {
if (!file_exists($this->sourcePath)) {
$this->errors[] = "源文件不存在:{$this->sourcePath}";
return;
}
$info = getimagesize($this->sourcePath);
if (!$info) {
$this->errors[] = "無法識別圖片格式或文件損壞";
return;
}
[$width, $height, $type] = $info;
$this->sourceInfo = [
'width' => $width,
'height' => $height,
'type' => $type,
'mime' => image_type_to_mime_type($type),
];
// 根據類型創建 GD 資源
switch ($type) {
case IMAGETYPE_JPEG:
$this->image = imagecreatefromjpeg($this->sourcePath);
break;
case IMAGETYPE_PNG:
$this->image = imagecreatefrompng($this->sourcePath);
// 保持透明度
imagealphablending($this->image, false);
imagesavealpha($this->image, true);
break;
case IMAGETYPE_GIF:
$this->image = imagecreatefromgif($this->sourcePath);
break;
case IMAGETYPE_WEBP:
$this->image = imagecreatefromwebp($this->sourcePath);
break;
default:
$this->errors[] = "不支援的圖片類型:{$this->sourceInfo['mime']}";
}
}
/**
* 智能縮放:保持比例填充目標區域,超出部分裁剪(適合圖標)
* @param int $targetW 目標寬度
* @param int $targetH 目標高度
* @return self 鏈式調用
*/
public function resizeCover(int $targetW, int $targetH): self {
if (!$this->image || $this->errors) return $this;
$srcW = $this->sourceInfo['width'];
$srcH = $this->sourceInfo['height'];
// 計算縮放比例:取較大者以覆蓋目標區域
$scale = max($targetW / $srcW, $targetH / $srcH);
$newW = (int)round($srcW * $scale);
$newH = (int)round($srcH * $scale);
// 創建目標畫布
$dest = imagecreatetruecolor($targetW, $targetH);
// 保持透明度(PNG/WebP)
if (in_array($this->sourceInfo['type'], [IMAGETYPE_PNG, IMAGETYPE_WEBP])) {
imagealphablending($dest, false);
imagesavealpha($dest, true);
$transparent = imagecolorallocatealpha($dest, 0, 0, 0, 127);
imagefill($dest, 0, 0, $transparent);
}
// 計算居中裁剪偏移
$srcX = (int)(($newW - $targetW) / 2);
$srcY = (int)(($newH - $targetH) / 2);
// 先縮放到臨時畫布,再裁剪到目標
$temp = imagecreatetruecolor($newW, $newH);
if (in_array($this->sourceInfo['type'], [IMAGETYPE_PNG, IMAGETYPE_WEBP])) {
imagealphablending($temp, false);
imagesavealpha($temp, true);
}
imagecopyresampled($temp, $this->image, 0, 0, 0, 0, $newW, $newH, $srcW, $srcH);
imagecopy($dest, $temp, 0, 0, $srcX, $srcY, $targetW, $targetH);
imagedestroy($temp);
$this->image = $dest;
$this->sourceInfo['width'] = $targetW;
$this->sourceInfo['height'] = $targetH;
return $this;
}
/**
* 等比縮放(不裁剪,含留白)
*/
public function resizeContain(int $maxW, int $maxH, array $bgColor = [255,255,255]): self {
if (!$this->image || $this->errors) return $this;
$srcW = $this->sourceInfo['width'];
$srcH = $this->sourceInfo['height'];
$scale = min($maxW / $srcW, $maxH / $srcH);
$newW = (int)round($srcW * $scale);
$newH = (int)round($srcH * $scale);
$dest = imagecreatetruecolor($maxW, $maxH);
$bg = imagecolorallocate($dest, ...$bgColor);
imagefill($dest, 0, 0, $bg);
$x = (int)(($maxW - $newW) / 2);
$y = (int)(($maxH - $newH) / 2);
imagecopyresampled($dest, $this->image, $x, $y, 0, 0, $newW, $newH, $srcW, $srcH);
$this->image = $dest;
$this->sourceInfo['width'] = $maxW;
$this->sourceInfo['height'] = $maxH;
return $this;
}
/**
* 添加水印
* @param string $markPath 水印圖片路徑
* @param int $opacity 透明度 0-100
* @param string $position 九宮格位置:tl/tc/tr/ml/mc/mr/bl/bc/br
*/
public function watermark(string $markPath, int $opacity = 50, string $position = 'br'): self {
if (!$this->image || $this->errors || !file_exists($markPath)) return $this;
$markInfo = getimagesize($markPath);
if (!$markInfo) return $this;
[$mW, $mH, $mType] = $markInfo;
switch ($mType) {
case IMAGETYPE_JPEG: $mark = imagecreatefromjpeg($markPath); break;
case IMAGETYPE_PNG: $mark = imagecreatefrompng($markPath); break;
case IMAGETYPE_GIF: $mark = imagecreatefromgif($markPath); break;
default: return $this;
}
$srcW = imagesx($this->image);
$srcH = imagesy($this->image);
// 計算水印位置
$positions = [
'tl' => [0, 0], 'tc' => [($srcW-$mW)/2, 0], 'tr' => [$srcW-$mW, 0],
'ml' => [0, ($srcH-$mH)/2], 'mc' => [($srcW-$mW)/2, ($srcH-$mH)/2], 'mr' => [$srcW-$mW, ($srcH-$mH)/2],
'bl' => [0, $srcH-$mH], 'bc' => [($srcW-$mW)/2, $srcH-$mH], 'br' => [$srcW-$mW, $srcH-$mH],
];
[$dx, $dy] = $positions[$position] ?? $positions['br'];
$dx = max(0, (int)$dx);
$dy = max(0, (int)$dy);
imagecopymerge($this->image, $mark, $dx, $dy, 0, 0, $mW, $mH, $opacity);
imagedestroy($mark);
return $this;
}
/**
* 輸出圖片到文件或瀏覽器
* @param string|null $destPath 文件路徑,null 直接輸出瀏覽器
* @param int $quality 畫質 0-100 (JPEG/WebP) 或 0-9 (PNG)
* @param int $format 輸出格式常量 IMAGETYPE_*,null 保持源格式
*/
public function output(?string $destPath = null, int $quality = 90, int $format = null): bool {
if (!$this->image || $this->errors) return false;
$format = $format ?? $this->sourceInfo['type'];
$funcMap = [
IMAGETYPE_JPEG => ['imagejpeg', $quality],
IMAGETYPE_PNG => ['imagepng', (int)round($quality / 10) - 1], // 0-9
IMAGETYPE_GIF => ['imagegif', null],
IMAGETYPE_WEBP => ['imagewebp', $quality],
];
if (!isset($funcMap[$format])) return false;
[$func, $qual] = $funcMap[$format];
if ($destPath) {
$dir = dirname($destPath);
if (!is_dir($dir)) mkdir($dir, 0755, true);
return $func($this->image, $destPath, $qual);
} else {
header('Content-Type: ' . image_type_to_mime_type($format));
return $func($this->image, null, $qual);
}
}
/**
* 批量生成所有規範尺寸並打包 ZIP
*/
public function generateIconSet(string $outputDir, string $zipName = 'app-icons.zip'): string|false {
if ($this->errors) return false;
$zip = new ZipArchive();
$zipPath = $outputDir . '/' . $zipName;
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
return false;
}
foreach (self::ICON_SPECS as $key => [$w, $h, $filename]) {
// 複製實例避免狀態汙染
$clone = clone $this;
$clone->resizeCover($w, $h);
$filePath = $outputDir . '/' . $filename;
$clone->output($filePath);
if (file_exists($filePath)) {
$zip->addFile($filePath, $filename);
unlink($filePath); // 清理臨時文件
}
}
$zip->close();
return file_exists($zipPath) ? $zipPath : false;
}
public function getErrors(): array { return $this->errors; }
public function hasErrors(): bool { return !empty($this->errors); }
}
?>
<?php
// generate_icons.php
require_once 'ImageProcessor.php';
$sourceFile = __DIR__ . '/source/logo.png'; // 設計師提供的 1024x1024 源圖
$outputDir = __DIR__ . '/output/icons_' . date('Ymd_His');
$processor = new ImageProcessor($sourceFile);
if ($processor->hasErrors()) {
die("載入失敗: " . implode(', ', $processor->getErrors()));
}
// 生成並打包
$zipPath = $processor->generateIconSet($outputDir);
if ($zipPath) {
echo "成功生成圖標包:{$zipPath}\n";
echo "文件大小: " . number_format(filesize($zipPath) / 1024, 1) . " KB\n";
// 可選:提供下載後刪除
// header('Content-Type: application/zip');
// header('Content-Disposition: attachment; filename="' . basename($zipPath) . '"');
// readfile($zipPath);
// unlink($zipPath); rmdir($outputDir);
} else {
echo "生成失敗\n";
}
?>
<?php
// upload_icon.php
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['icon'])) {
$file = $_FILES['icon'];
if ($file['error'] !== UPLOAD_ERR_OK) {
die('上傳失敗: ' . $file['error']);
}
// 驗證
$allowed = [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_WEBP];
$info = getimagesize($file['tmp_name']);
if (!$info || !in_array($info[2], $allowed)) {
die('僅支援 PNG/JPG/WebP 格式');
}
if ($info[0] < 1024 || $info[1] < 1024) {
die('源圖尺寸至少 1024x1024');
}
$processor = new ImageProcessor($file['tmp_name']);
$zipPath = $processor->generateIconSet(sys_get_temp_dir() . '/icon_gen_' . uniqid());
if ($zipPath) {
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="app-icons-' . date('Ymd') . '.zip"');
readfile($zipPath);
unlink($zipPath);
exit;
}
die('生成失敗');
}
?>
<!DOCTYPE html>
<html><body>
<h2>App 圖標批量生成器</h2>
<form method="post" enctype="multipart/form-data">
<input type="file" name="icon" accept="image/png,image/jpeg,image/webp" required>
<button type="submit">生成並下載所有尺寸</button>
</form>
<p>建議上傳 1024x1024 或更大的正方形 PNG 圖片(支援透明背景)</p>
</body></html>
optipng、jpegoptim、svgo 壓縮輸出體積imagick 或 rsvg-convert 先光柵化再處理本文提供的 ImageProcessor 類別封裝了 GD 庫的核心操作,實現了 App 圖標批量生成的完整流程:智能縮放裁剪(Cover 模式)、水印、多格式輸出、ZIP 打包下載。代碼結構清晰、錯誤處理完善、易於擴展,可直接集成到 CI/CD 流水線、管理後台或獨立服務中。對於高併發或向量源場景,建議引入 ImageMagick (imagick 擴展) 或雲端圖片處理服務(如 Cloudinary、Imgix)獲得更強性能與功能。