English | 简体中文 | 繁體中文
查询

imagecolorexact()函数—用法及示例

「 在调色板中查找与指定的 RGB 值最接近的颜色索引 」


函数名:imagecolorexact()

适用版本:PHP 4, PHP 5, PHP 7

用法:imagecolorexact() 函数用于在调色板中查找与指定的 RGB 值最接近的颜色索引。它返回找到的颜色索引或者如果出错则返回-1。

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

参数:

  • $image:必需,图像资源,通过 imagecreate() 或 imagecreatefrom*() 函数创建。
  • $red:必需,指定红色分量的值(0-255)。
  • $green:必需,指定绿色分量的值(0-255)。
  • $blue:必需,指定蓝色分量的值(0-255)。

返回值:返回找到的颜色索引,如果未找到则返回-1。

示例:

// 创建一个新的画布
$image = imagecreatetruecolor(200, 200);

// 定义颜色
$red = imagecolorallocate($image, 255, 0, 0); // 红色
$green = imagecolorallocate($image, 0, 255, 0); // 绿色
$blue = imagecolorallocate($image, 0, 0, 255); // 蓝色

// 获取与指定 RGB 值最接近的颜色索引
$closestColorIndex = imagecolorexact($image, 255, 0, 0);

// 输出结果
echo "Closest color index: " . $closestColorIndex;

// 销毁图像资源
imagedestroy($image);

输出结果: Closest color index: 0

以上示例创建了一个200x200的画布,并定义了红色、绿色和蓝色。然后使用 imagecolorexact() 函数找到与 RGB 值 (255, 0, 0) 最接近的颜色索引,并将结果输出。在这个示例中,红色的颜色索引是0,所以输出结果为0。

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