首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 縮放 GIF/PNG 透明背景變黑色的解決方案

     編輯:PHP 綜合知識

問題現象

使用 imagecreatetruecolor() 建立真彩色畫布,再以 imagecopyresampled() 縮放 GIF/PNG 透明圖片時,原本透明區域變成黑色。

根本原因

imagecreatetruecolor() 建立的畫布預設為黑色背景(RGB 0,0,0),且未啟用 Alpha 通道混合。直接複製貼上透明圖片時,透明資訊丟失。

解決方法:建立透明畫布並啟用 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 通道資訊

注意事項

  • GIF 為調色盤模式,PNG 為真彩色模式,處理方式略有不同
  • 縮放後輸出 GIF 可能因調色盤限制導致畫質下降,建議輸出 PNG
  • 大量處理圖片時注意 imagedestroy() 釋放記憶體

總結

核心在於:建立目標畫布時預先填充透明色、啟用 Alpha 混合、保存 Alpha 通道三步驟。掌握此模式即可解決所有 GD 庫縮放透明圖片背景變黑的問題。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved