在 PHP 中,使用 imagecolorallocate() 函數為圖像分配顏色時,不支持透明度。要處理透明度,您需要使用 GD 庫的 imagecolorallocatealpha() 函數。這個函數允許您分配一個 alpha 值(透明度)給顏色。
以下是使用 imagecolorallocatealpha() 的示例:
<?php
// 創建圖像
$image = imagecreatetruecolor(200, 200);
// 為圖像分配背景顏色(白色)
$bg = imagecolorallocatealpha($image, 255, 255, 255, 127); // 最后一個參數是 alpha 值,范圍從 0(完全透明)到 127(完全不透明)
imagefill($image, 0, 0, $bg);
// 為圖像分配前景顏色(紅色,帶透明度)
$fg = imagecolorallocatealpha($image, 255, 0, 0, 64); // 最后一個參數是 alpha 值,范圍從 0(完全透明)到 127(完全不透明)
// 在圖像上繪制一個矩形
imagettftext($image, 20, 0, 50, 100, $fg, 'arial.ttf', 'Hello, World!');
// 輸出圖像
header('Content-type: image/png');
imagepng($image);
// 銷毀圖像資源
imagedestroy($image);
?>
在這個示例中,我們首先創建了一個 200x200 的圖像。然后,我們使用 imagecolorallocatealpha() 函數為背景顏色分配了透明度(127)。接下來,我們為前景顏色(紅色)分配了透明度(64)。最后,我們在圖像上繪制了一個帶有透明度的矩形,并將圖像輸出到瀏覽器。