imagecolorsforindex
获取索引的颜色
PHP 4 >= 4.0.0, PHP 5, PHP 7, PHP 8
imagecolorsforindex() 函数用于返回与指定颜色索引值对应的 RGB 颜色信息。
array imagecolorsforindex(resource $image, int $index)
返回一个包含“red”、“green”、“blue”和“alpha”键的关联数组,分别表示颜色的红色、绿色、蓝色和透明度分量。如果索引无效或发生错误,返回 false。
以下是如何使用 imagecolorsforindex() 函数的示例代码:
<?php $image = imagecreate(100, 100); // 创建一个 100x100 的图像 $color = imagecolorallocate($image, 255, 0, 0); // 分配红色 imagesetpixel($image, 50, 50, $color); // 在图像的 (50,50) 位置设置像素颜色 <p>$colorIndex = imagecolorat($image, 50, 50); // 获取 (50, 50) 位置的颜色索引值<br> $rgb = imagecolorsforindex($image, $colorIndex); // 获取该颜色的 RGB 值</p> <p>echo "红色: " . $rgb['red'] . "<br>";<br> echo "绿色: " . $rgb['green'] . "<br>";<br> echo "蓝色: " . $rgb['blue'] . "<br>";<br> echo "透明度: " . $rgb['alpha'] . "<br>";</p> <p>imagedestroy($image); // 释放图像资源<br> ?><br>
首先,通过 imagecreate() 函数创建一个 100x100 的图像,并用 imagecolorallocate() 函数分配一个红色。接着,使用 imagesetpixel() 在图像的 (50, 50) 位置设置红色的像素。通过 imagecolorat() 获取该像素的颜色索引,然后调用 imagecolorsforindex() 获取该颜色的 RGB 和透明度信息,并将结果显示出来。