直接使用 imagecopyresampled 縮放 PNG 時,若未正確處理 Alpha 通道,透明區域會變成黑色或白色背景。關鍵在於建立真彩色畫布後,必須先填充全透明色彩,並啟用 imagesavealpha。
<?php
// 1. 載入原圖
$srcImg = imagecreatefrompng('./src.png');
$srcW = imagesx($srcImg);
$srcH = imagesy($srcImg);
// 2. 計算目標尺寸(這裡示範縮小一半)
$dstW = (int)round($srcW * 0.5);
$dstH = (int)round($srcH * 0.5);
// 3. 建立真彩色目標畫布
$dstImg = imagecreatetruecolor($dstW, $dstH);
// 4. 關鍵步驟:分配「全透明」顏色並填滿畫布
$transparent = imagecolorallocatealpha($dstImg, 0, 0, 0, 127); // 127 = 完全透明
imagefill($dstImg, 0, 0, $transparent);
// 5. 啟用 Alpha 通道保存(必須在輸出前呼叫)
imagesavealpha($dstImg, true);
// 6. 高品質重採樣縮放
imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
// 7. 輸出 PNG
imagepng($dstImg, './dst.png');
// 8. 釋放資源
imagedestroy($srcImg);
imagedestroy($dstImg);
| 函式 | 作用 | 關鍵參數 |
|---|---|---|
| imagecreatetruecolor | 建立真彩色畫布(支援 Alpha) | 寬、高 |
| imagecolorallocatealpha | 分配含 Alpha 的顏色 | R, G, B, Alpha(0-127) |
| imagefill | 填充畫布背景 | 座標 (0,0) + 透明色 |
| imagesavealpha | 開啟/關閉 Alpha 通道保存 | true = 保存完整透明資訊 |
| imagecopyresampled | 高品質重採樣縮放 | 目標/來源座標與尺寸 |
imagecreate(調色盤模式)而非 imagecreatetruecolor → 導致透明資訊遺失。imagesavealpha($dstImg, true) 位置在 imagecopyresampled 之後 → 必須在縮放前啟用。imagefill 透明色 → 新畫布預設黑色背景污染透明區。function resizePngKeepAlpha(string $srcPath, string $dstPath, float $scale): bool {
$src = @imagecreatefrompng($srcPath);
if (!$src) return false;
$sw = imagesx($src); $sh = imagesy($src);
$dw = max(1, (int)round($sw * $scale));
$dh = max(1, (int)round($sh * $scale));
$dst = imagecreatetruecolor($dw, $dh);
$alpha = imagecolorallocatealpha($dst, 0, 0, 0, 127);
imagefill($dst, 0, 0, $alpha);
imagesavealpha($dst, true);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $dw, $dh, $sw, $sh);
$ok = imagepng($dst, $dstPath);
imagedestroy($src); imagedestroy($dst);
return (bool)$ok;
}