GD 庫縮放 GIF 時常出現「黑色背景」問題,因透明色索引未正確轉移。本文提供一個完整的 ResizeImage 類,解決等比縮放、透明色保持、資源管理三大核心問題,開箱即用。
imagecreatetruecolor() 創建真彩色畫布,無調色板,直接複製會丟失透明索引<?php
/**
* 圖片等比縮放類,完美支持 GIF 透明背景
* 依賴:GD 擴展 (php_gd2.dll)
*/
class ResizeImage {
private int $srcWidth;
private int $srcHeight;
private int $dstWidth;
private int $dstHeight;
private string $srcPath;
private string $dstPath;
private resource $srcImage;
private resource $dstImage;
private float $scale = 0.5; // 默認縮放比例 50%
public function __construct(string $srcPath, string $dstPath, float $scale = 0.5) {
$this->srcPath = $srcPath;
$this->dstPath = $dstPath;
$this->scale = $scale;
[$this->srcWidth, $this->srcHeight] = getimagesize($srcPath);
$this->calculateDimensions();
}
/** 計算目標尺寸,保持長寬比 */
private function calculateDimensions(): void {
$this->dstWidth = (int)($this->srcWidth * $this->scale);
$this->dstHeight = (int)($this->srcHeight * $this->scale);
// 修正:若按寬度縮放超高,則按高度基準反算寬度
if ($this->dstWidth > 0 && $this->srcWidth < $this->srcHeight) {
$this->dstWidth = (int)(($this->dstHeight / $this->srcHeight) * $this->srcWidth);
} else {
$this->dstHeight = (int)(($this->dstWidth / $this->srcWidth) * $this->srcHeight);
}
}
/** 執行縮放並保存 */
public function save(): bool {
// 1. 載入源圖 (自動識別格式)
$this->srcImage = $this->createImageFromFile($this->srcPath);
if (!$this->srcImage) return false;
// 2. 創建目標畫布 (真彩色)
$this->dstImage = imagecreatetruecolor($this->dstWidth, $this->dstHeight);
// 3. 【關鍵】保持 GIF 透明背景
$this->preserveTransparency();
// 4. 高質量重採樣縮放
imagecopyresampled(
$this->dstImage, $this->srcImage,
0, 0, 0, 0,
$this->dstWidth, $this->dstHeight,
$this->srcWidth, $this->srcHeight
);
// 5. 保存 (根據擴展名自動選擇格式)
$result = $this->saveImage($this->dstImage, $this->dstPath);
// 6. 釋放資源
$this->destroy();
return $result;
}
/** 識別格式並載入 */
private function createImageFromFile(string $path): ?resource {
$mime = mime_content_type($path);
return match ($mime) {
'image/gif' => imagecreatefromgif($path),
'image/jpeg' => imagecreatefromjpeg($path),
'image/png' => imagecreatefrompng($path),
'image/webp' => imagecreatefromwebp($path),
default => null,
};
}
/** 核心:保持透明度 */
private function preserveTransparency(): void {
// 僅 GIF/PNG 需要處理透明度
if (!in_array(mime_content_type($this->srcPath), ['image/gif', 'image/png'])) {
return;
}
// 獲取源圖透明色索引
$transparentIndex = imagecolortransparent($this->srcImage);
// 索引有效且在調色板範圍內
if ($transparentIndex >= 0 && $transparentIndex < imagecolorstotal($this->srcImage)) {
// 獲取該索引的 RGB 值
$rgb = imagecolorsforindex($this->srcImage, $transparentIndex);
// 在目標畫布分配相同顏色
$newTransparent = imagecolorallocate(
$this->dstImage,
$rgb['red'], $rgb['green'], $rgb['blue']
);
// 填充整個畫布為該透明色
imagefill($this->dstImage, 0, 0, $newTransparent);
// 設置目標畫布透明色
imagecolortransparent($this->dstImage, $newTransparent);
}
// PNG 額外處理:開啟 Alpha 混合,保存完整 Alpha 通道
if (mime_content_type($this->srcPath) === 'image/png') {
imagealphablending($this->dstImage, false);
imagesavealpha($this->dstImage, true);
}
}
/** 根據擴展名保存 */
private function saveImage(resource $image, string $path): bool {
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
return match ($ext) {
'gif' => imagegif($image, $path),
'jpg', 'jpeg' => imagejpeg($image, $path, 90),
'png' => imagepng($image, $path, 6), // 壓縮級別 0-9
'webp' => imagewebp($image, $path, 85),
default => false,
};
}
/** 銷毀資源 */
private function destroy(): void {
if ($this->srcImage) imagedestroy($this->srcImage);
if ($this->dstImage) imagedestroy($this->dstImage);
}
/** 靜態快捷方法 */
public static function resize(string $src, string $dst, float $scale = 0.5): bool {
return (new self($src, $dst, $scale))->save();
}
}
<?php
require_once 'ResizeImage.php';
// 1. 基礎用法:縮放 50%
ResizeImage::resize('uploads/avatar.gif', 'thumbs/avatar.gif', 0.5);
// 2. 指定目標寬度,自動計算高度
$resize = new ResizeImage('source/animation.gif', 'output/small.gif');
$resize->setTargetWidth(200); // 需添加 setter 方法
$resize->save();
// 3. 批量處理目錄
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('uploads'));
foreach ($iterator as $file) {
if ($file->isFile() && in_array($file->getExtension(), ['gif','png','jpg','webp'])) {
$dst = 'thumbs/' . $file->getBasename();
ResizeImage::resize($file->getPathname(), $dst, 0.3);
}
}
<?php
// 在類中添加
public function setTargetWidth(int $width): self {
$this->scale = $width / $this->srcWidth;
$this->calculateDimensions();
return $this;
}
public function setTargetHeight(int $height): self {
$this->scale = $height / $this->srcHeight;
$this->calculateDimensions();
return $this;
}
public function setTargetSize(int $width, int $height, bool $keepRatio = true): self {
if ($keepRatio) {
$ratio = min($width / $this->srcWidth, $height / $this->srcHeight);
$this->dstWidth = (int)($this->srcWidth * $ratio);
$this->dstHeight = (int)($this->srcHeight * $ratio);
} else {
$this->dstWidth = $width;
$this->dstHeight = $height;
}
return $this;
}
| 函數 | 質量 | 速度 | 用途 |
|---|---|---|---|
imagecopyresized | 低 (鋸齒) | 快 | 縮略圖、預覽 |
imagecopyresampled | 高 (雙立方插值) | 中 | 生產環境、最終輸出 |
imagescale (PHP 5.5+) | 高 | 快 (C 級優化) | 簡單縮放、單行代碼 |
關鍵點:識別格式 → 創建真彩畫布 → 提取源透明色 RGB → 目標畫布分配同色 → 填充背景 → 設置透明色 → 高質量重採樣 → 保存。此類封裝了完整邏輯,支持 GIF/PNG 透明、JPEG/WebP 質量控制、多種尺寸模式,可直接投入生產使用。