使用 imagecreatetruecolor() 建立真彩色畫布,再以 imagecopyresampled() 縮放 GIF/PNG 透明圖片時,原本透明區域變成黑色。
imagecreatetruecolor() 建立的畫布預設為黑色背景(RGB 0,0,0),且未啟用 Alpha 通道混合。直接複製貼上透明圖片時,透明資訊丟失。
$img = imagecreatetruecolor(200, 200);
// 1. 分配白色(或任意色)作為透明色
$transparentColor = imagecolorallocate($img, 255, 255, 255);
// 2. 設定該顏色為透明色
imagecolortransparent($img, $transparentColor);
// 3. 填充畫布為透明色
imagefill($img, 0, 0, $transparentColor);
// 4. 關鍵:啟用 Alpha 混合模式
imagealphablending($img, true);
imagesavealpha($img, true);
// 之後進行 imagecopyresampled() 和 imagecopymerge() 即可保持透明
function resizeTransparentImage($srcPath, $dstPath, $maxWidth, $maxHeight) {
list($srcW, $srcH, $srcType) = getimagesize($srcPath);
if ($srcType !== IMAGETYPE_GIF && $srcType !== IMAGETYPE_PNG) {
return false; // 僅處理 GIF/PNG
}
// 建立來源圖片資源
$srcImg = ($srcType === IMAGETYPE_GIF)
? imagecreatefromgif($srcPath)
: imagecreatefrompng($srcPath);
// 計算目標尺寸(保持比例)
$ratio = min($maxWidth / $srcW, $maxHeight / $srcH);
$dstW = (int)($srcW * $ratio);
$dstH = (int)($srcH * $ratio);
// 建立透明目標畫布
$dstImg = imagecreatetruecolor($dstW, $dstH);
$transparent = imagecolorallocatealpha($dstImg, 255, 255, 255, 127);
imagefill($dstImg, 0, 0, $transparent);
imagealphablending($dstImg, true);
imagesavealpha($dstImg, true);
// 縮放複製
imagecopyresampled($dstImg, $srcImg, 0, 0, 0, 0, $dstW, $dstH, $srcW, $srcH);
// 輸出
$result = ($srcType === IMAGETYPE_GIF)
? imagegif($dstImg, $dstPath)
: imagepng($dstImg, $dstPath);
imagedestroy($srcImg);
imagedestroy($dstImg);
return $result;
}
| 函數 | 作用 |
|---|---|
imagecolortransparent() | 指定調色盤索引為透明色(調色盤模式) |
imagecolorallocatealpha() | 分配帶 Alpha 通道的顏色(真彩色模式,127 為全透明) |
imagealphablending() | 啟用/停用 Alpha 混合 |
imagesavealpha() | 儲存時保留 Alpha 通道資訊 |
imagedestroy() 釋放記憶體核心在於:建立目標畫布時預先填充透明色、啟用 Alpha 混合、保存 Alpha 通道三步驟。掌握此模式即可解決所有 GD 庫縮放透明圖片背景變黑的問題。