PHP imagecolorclosestalpha - Get the index of the color closest to the specified color with transparency

PHP 图像处理PHP Image Processing

imagecolorclosestalpha — Get the index of the color closest to the specified color with transparency.

Syntax

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

Returns the color in the image palette that is "closest" to the specified RGB value and alpha depth.

Parameters

  • imageThe image resource returned by an image creation function (such as imagecreatetruecolor()).
  • redThe value of the red component.
  • greenThe value of the green component.
  • blueThe value of the blue component.
  • alphaA value between 0 and 127. 0 means completely opaque, 127 means completely transparent.

Color parameters are integers between 0 and 255, or hexadecimal numbers between 0x00 and 0xFF.

Return Value

Returns the index of the closest color in the palette.

Example

Search for a set of colors in an image.

<?php
// 从一个图像开始,并将其转换为一个基于调色板的图像
$im = imagecreatefrompng('figures/imagecolorclosest.png');
imagetruecolortopalette($im, false, 255);

// 搜索颜色 (RGB)
$colors = array(
    array(254, 145, 154, 50),
    array(153, 145, 188, 127),
    array(153, 90, 145, 0),
    array(255, 137, 92, 84)
);

// 循环遍历,查找调色板中最接近的颜色
// 返回搜索次数,搜索的 RGB 和最接近的匹配的 RGB
foreach($colors as $id => $rgb)
{
    $result = imagecolorclosestalpha($im, $rgb[0], $rgb[1], $rgb[2], $rgb[3]);
    $result = imagecolorsforindex($im, $result);
    $result = "({$result['red']}, {$result['green']}, {$result['blue']}, {$result['alpha']})";

    echo "#$id: 搜索 ($rgb[0], $rgb[1], $rgb[2], $rgb[3]); 最接近的匹配: $result。\n";
}

imagedestroy($im);
?>

The output of the above example is similar to:

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

Related Articles

PHP 图像处理PHP Image Processing

Other Extensions