查询

imagecolorallocatealpha()函数—用法及示例

「 为图像资源分配一个带有透明度的颜色 」


函数名:imagecolorallocatealpha()

适用版本:PHP 4 >= 4.0.6, PHP 5, PHP 7

用法: imagecolorallocatealpha() 函数用于为图像资源分配一个带有透明度的颜色。该函数返回一个标识颜色的索引值,可以在后续图像绘制操作中使用。

语法: imagecolorallocatealpha(resource $image, int $red, int $green, int $blue, int $alpha): int

参数:

  • $image:表示图像资源的标识符,通常由 imagecreatetruecolor() 创建。
  • $red:整数类型,表示红色分量的值,取值范围为 0-255。
  • $green:整数类型,表示绿色分量的值,取值范围为 0-255。
  • $blue:整数类型,表示蓝色分量的值,取值范围为 0-255。
  • $alpha:整数类型,表示透明度的值,取值范围为 0(完全透明)到 127(完全不透明)。

返回值: 该函数返回一个整数值,表示颜色的索引。

示例:

// 创建一个 200x200 的图像资源
$image = imagecreatetruecolor(200, 200);

// 分配一个带有透明度的红色
$color = imagecolorallocatealpha($image, 255, 0, 0, 50);

// 在图像上绘制一个带有透明度的红色矩形
imagefilledrectangle($image, 50, 50, 150, 150, $color);

// 设置图像的颜色模式为 alpha
imagesavealpha($image, true);

// 输出图像到浏览器
header('Content-Type: image/png');
imagepng($image);

// 释放图像资源
imagedestroy($image);

以上示例中,我们首先创建了一个 200x200 的图像资源。然后使用 imagecolorallocatealpha() 函数分配了一个带有透明度的红色,透明度为 50。接着使用 imagefilledrectangle() 函数在图像上绘制了一个带有透明度的红色矩形。最后,通过设置图像的颜色模式为 alpha,并使用 imagepng() 函数输出图像到浏览器。最后别忘了释放图像资源使用 imagedestroy() 函数。

补充纠错
上一个函数: ibase_wait_event()函数
下一个函数: imagecharup()函数
热门PHP函数
分享链接