使用 `imagecreatetruecolor()` 建立畫布後直接 `imagecopyresampled()` 貼上透明 PNG/GIF,背景會變黑(預設黑色填充)。必須**啟用 Alpha 混合、分配透明色、填充透明背景**三步驟。
<?php
$dst = imagecreatetruecolor(200, 200);
$src = imagecreatefrompng('transparent.png');
imagecopyresampled($dst, $src, 0,0, 0,0, 200,200, imagesx($src), imagesy($src));
imagepng($dst, 'out.png'); // 背景變黑!
?>
<?php
$src = imagecreatefrompng('transparent.png'); // 或 imagecreatefromgif/webp
$srcW = imagesx($src); $srcH = imagesy($src);
$dst = imagecreatetruecolor(200, 200);
// 1. 啟用 Alpha 混合模式(關鍵)
imagealphablending($dst, true);
// 2. 分配全透明色並填充畫布
$transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127); // 127 = 完全透明
imagefill($dst, 0, 0, $transparent);
// 3. 關鍵:保存 Alpha 通道資訊(輸出時生效)
imagesavealpha($dst, true);
// 4. 縮放/裁切貼上
imagecopyresampled($dst, $src, 0,0, 0,0, 200,200, $srcW, $srcH);
// 輸出
header('Content-Type: image/png');
imagepng($dst);
imagedestroy($src);
imagedestroy($dst);
?>
<?php
function resizeTransparent(string $srcPath, int $w, int $h, string $dstPath, string $mode = 'crop', int $quality = 90): bool
{
$info = @getimagesize($srcPath);
if (!$info) return false;
[$sw, $sh, $type] = $info;
$src = match ($type) {
IMAGETYPE_PNG => imagecreatefrompng($srcPath),
IMAGETYPE_GIF => imagecreatefromgif($srcPath),
IMAGETYPE_WEBP => imagecreatefromwebp($srcPath),
default => null,
};
if (!$src) return false;
$dst = imagecreatetruecolor($w, $h);
imagealphablending($dst, true);
$tp = imagecolorallocatealpha($dst, 255, 255, 255, 127);
imagefill($dst, 0, 0, $tp);
imagesavealpha($dst, true);
if ($mode === 'crop') {
$srcRatio = $sw / $sh;
$dstRatio = $w / $h;
if ($srcRatio > $dstRatio) {
$cw = $sh * $dstRatio; $ch = $sh;
$sx = ($sw - $cw) / 2; $sy = 0;
} else {
$cw = $sw; $ch = $sw / $dstRatio;
$sx = 0; $sy = ($sh - $ch) / 2;
}
imagecopyresampled($dst, $src, 0, 0, $sx, $sy, $w, $h, $cw, $ch);
} else { // scale: 等比縮放居中,不足留透明
$scale = min($w/$sw, $h/$sh);
$nw = (int)($sw * $scale); $nh = (int)($sh * $scale);
$dx = (int)(($w - $nw)/2); $dy = (int)(($h - $nh)/2);
imagecopyresampled($dst, $src, $dx, $dy, 0, 0, $nw, $nh, $sw, $sh);
}
$ok = match ($type) {
IMAGETYPE_PNG => imagepng($dst, $dstPath, min(9, (int)($quality/10))),
IMAGETYPE_GIF => imagegif($dst, $dstPath),
IMAGETYPE_WEBP => imagewebp($dst, $dstPath, $quality),
default => false,
};
imagedestroy($src);
imagedestroy($dst);
return $ok;
}
?>
記住:**開啟混合 → 填充透明 → 保存 Alpha**,透明背景永不變黑。