PHP imagecolorclosestalpha - 取得与指定的颜色加透明度最接近的颜色的索引


imagecolorclosestalpha — 取得与指定的颜色加透明度最接近的颜色的索引。

语法

  1. int imagecolorclosestalpha ( resource $image , int $red , int $green , int $blue , int $alpha )

返回图像调色板中与指定的 RGB 值以及 alpha 深度最"接近"的颜色。

参数

  • image 由图像创建函数(例如 imagecreatetruecolor())返回的图像资源。
  • red 红色成分的值。
  • green 绿色成分的值。
  • blue 蓝色成分的值。
  • alpha 一个介于 0 和 127 之间的值。0 表示完全不透明,127 表示完全透明。

颜色参数是介于 0 和 255 之间的整数,或者是介于 0x00 和 0xFF 之间的十六进制数。

返回值

返回调色板中最接近的颜色的索引。

实例

搜索图像中的一组颜色。

  1. <?php
  2. // 从一个图像开始,并将其转换为一个基于调色板的图像
  3. $im = imagecreatefrompng('figures/imagecolorclosest.png');
  4. imagetruecolortopalette($im, false, 255);
  5.  
  6. // 搜索颜色 (RGB)
  7. $colors = array(
  8.     array(254, 145, 154, 50),
  9.     array(153, 145, 188, 127),
  10.     array(153, 90, 145, 0),
  11.     array(255, 137, 92, 84)
  12. );
  13.  
  14. // 循环遍历,查找调色板中最接近的颜色
  15. // 返回搜索次数,搜索的 RGB 和最接近的匹配的 RGB
  16. foreach($colors as $id => $rgb)
  17. {
  18.     $result = imagecolorclosestalpha($im, $rgb[0], $rgb[1], $rgb[2], $rgb[3]);
  19.     $result = imagecolorsforindex($im, $result);
  20.     $result = "({$result['red']}, {$result['green']}, {$result['blue']}, {$result['alpha']})";
  21.  
  22.     echo "#$id: 搜索 ($rgb[0], $rgb[1], $rgb[2], $rgb[3]); 最接近的匹配: $result。\n";
  23. }
  24.  
  25. imagedestroy($im);
  26. ?>

以上实例的输出类似于:

  1. #0: 搜索 (254, 145, 154, 50); 最接近的匹配: (252, 150, 148, 0)。
  2. #1: 搜索 (153, 145, 188, 127); 最接近的匹配: (148, 150, 196, 0)。
  3. #2: 搜索 (153, 90, 145, 0); 最接近的匹配: (148, 90, 156, 0)。
  4. #3: 搜索 (255, 137, 92, 84); 最接近的匹配: (252, 150, 92, 0)。