萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP GD 處理 GIF/PNG 透明背景變黑問題:正確保持 Alpha 通道的縮放裁切姿勢

使用 `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;
}
?>

常見誤區

  • 只設 `imagesavealpha(true)` 不 `imagefill` 透明色 → 仍黑。
  • 只 `imagefill` 不 `imagesavealpha` → 輸出時 Alpha 丟失。
  • JPEG 不支援透明,轉 JPEG 前需先合成白底或指定背景色。
  • `imagecopyresampled` 縮放品質優於 `imagecopyresized`,務必用前者。

記住:**開啟混合 → 填充透明 → 保存 Alpha**,透明背景永不變黑。

copyright © 萬盛學電腦網 all rights reserved