如果您只想提取顏色的 Alpha 值,您可以簡單地這樣提取:
<?php
$color = imagecolorat($im, 50, 50);
$alpha = $color >> 24;
?>
它實際上是將前 24 位元(其中每個顏色使用 8x3 位元)向右位移,並返回剩餘的 7 個已分配的位元(通常用於 Alpha)。
(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)
imagecolorallocatealpha — 為影像配置顏色
imagecolorallocatealpha() 的行為與 imagecolorallocate() 相同,但增加了透明度參數 alpha
。
image
一個 GdImage 物件,由其中一個影像建立函式返回,例如 imagecreatetruecolor()。
紅色
紅色成分的值。
綠色
綠色成分的值。
藍色
藍色成分的值。
alpha
介於 0
和 127
之間的值。 0
表示完全不透明,而 127
表示完全透明。
red
、green
和 blue
參數是介於 0 到 255 之間的整數,或介於 0x00 到 0xFF 之間的十六進位值。
顏色識別碼,如果配置失敗則為 false
。
範例 #1 使用 imagecolorallocatealpha() 的範例
<?php
$size = 300;
$image=imagecreatetruecolor($size, $size);
// something to get a white background with black border
$back = imagecolorallocate($image, 255, 255, 255);
$border = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 0, 0, $size - 1, $size - 1, $back);
imagerectangle($image, 0, 0, $size - 1, $size - 1, $border);
$yellow_x = 100;
$yellow_y = 75;
$red_x = 120;
$red_y = 165;
$blue_x = 187;
$blue_y = 125;
$radius = 150;
// allocate colors with alpha values
$yellow = imagecolorallocatealpha($image, 255, 255, 0, 75);
$red = imagecolorallocatealpha($image, 255, 0, 0, 75);
$blue = imagecolorallocatealpha($image, 0, 0, 255, 75);
// drawing 3 overlapped circle
imagefilledellipse($image, $yellow_x, $yellow_y, $radius, $radius, $yellow);
imagefilledellipse($image, $red_x, $red_y, $radius, $radius, $red);
imagefilledellipse($image, $blue_x, $blue_y, $radius, $radius, $blue);
// don't forget to output a correct header!
header('Content-Type: image/png');
// and finally, output the result
imagepng($image);
imagedestroy($image);
?>
上述範例的輸出會類似以下內容
範例 #2 轉換典型的 alpha 值以搭配 imagecolorallocatealpha() 使用
通常 alpha 值 0
表示完全透明的像素,且 alpha 通道有 8 位元。要將此類 alpha 值轉換為與 imagecolorallocatealpha() 相容,只需一些簡單的算術即可
<?php
$alpha8 = 0; // 完全透明
var_dump(127 - ($alpha8 >> 1));
$alpha8 = 255; // 完全不透明
var_dump(127 - ($alpha8 >> 1));
?>
上述範例將輸出
int(127) int(0)
如果您只想提取顏色的 Alpha 值,您可以簡單地這樣提取:
<?php
$color = imagecolorat($im, 50, 50);
$alpha = $color >> 24;
?>
它實際上是將前 24 位元(其中每個顏色使用 8x3 位元)向右位移,並返回剩餘的 7 個已分配的位元(通常用於 Alpha)。
如果您需要計算具有 Alpha 通道的顏色的整數表示形式,而無需初始化影像並使用 imagecolorallocatealpha 函式,那麼此函式可能會有幫助:
<?php
function alphaColor($hexColor,$alpha)
{
return bindec(decbin($alpha).decbin(hexdec($hexColor));
}
echo alphaColor("FFFFFF",127);
?>