當前位置: 首頁> 最新文章列表> 將imagecolorallocatealpha() 用在非truecolor 圖像上

將imagecolorallocatealpha() 用在非truecolor 圖像上

M66 2025-06-01

在PHP 中, imagecolorallocatealpha()函數用於為圖像分配帶有alpha(透明度)信息的顏色。但需要注意的是,這個函數。如果你嘗試在非truecolor 圖像(由imagecreate()創建的調色板圖像)上使用它,可能會遇到意料之外的行為或錯誤。

那麼,如何在非truecolor 圖像上間接使用imagecolorallocatealpha()的功能呢?本文將帶你了解其原理並提供實用的代碼示例。

1?? 理解truecolor 與調色板圖像

  • 調色板圖像(palette-based image)
    使用最多256 種顏色,每種顏色存儲在調色板中。通過imagecreate()創建。適合簡單圖形,但不支持真正的透明通道。

  • Truecolor 圖像<br> 每個像素獨立存儲RGB(紅綠藍)和alpha(透明度)值通過imagecreatetruecolor()創建。適合複雜圖形和需要透明度的場景。

由於imagecolorallocatealpha()涉及alpha 通道,所以它需要truecolor 圖像才能生效。

2?? 解決方案:先轉換為truecolor 圖像

如果你一開始使用imagecreate()創建了調色板圖像,可以在使用imagecolorallocatealpha()之前,將其轉換為truecolor 圖像。

示例代碼

<?php
// 創建一個調色板圖像
$paletteImage = imagecreate(200, 200);
$white = imagecolorallocate($paletteImage, 255, 255, 255);
$black = imagecolorallocate($paletteImage, 0, 0, 0);

// 將調色板圖像轉換為 truecolor 圖像
$truecolorImage = imagecreatetruecolor(imagesx($paletteImage), imagesy($paletteImage));
imagecopy($truecolorImage, $paletteImage, 0, 0, 0, 0, imagesx($paletteImage), imagesy($paletteImage));

// 分配一個帶透明度的顏色
$transparentRed = imagecolorallocatealpha($truecolorImage, 255, 0, 0, 64); // 64 表示半透明

// 使用這個顏色畫一個填充矩形
imagefilledrectangle($truecolorImage, 50, 50, 150, 150, $transparentRed);

// 設置保存為 PNG(支持透明度)
header('Content-Type: image/png');
imagepng($truecolorImage);

// 清理內存
imagedestroy($paletteImage);
imagedestroy($truecolorImage);
?>

注意事項

  • imagecreatetruecolor()創建的圖像默認是全黑背景,如果要保留原調色板圖像的背景,必須用imagecopy()

  • 輸出為PNG 格式才能保存alpha 通道(JPEG 不支持透明度)。

  • 透明度值alpha的範圍是0(完全不透明)到127(完全透明)。

3?? 另一個小技巧:直接用PNG 作為底圖

 <?php
$image = imagecreatefrompng('https://m66.net/images/sample.png');
$semiTransparentBlue = imagecolorallocatealpha($image, 0, 0, 255, 80);
imagefilledellipse($image, 100, 100, 80, 80, $semiTransparentBlue);

header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>