gpt4 book ai didi

php - PHP 中颜色之间的 "Distance"

转载 作者:IT王子 更新时间:2023-10-29 00:07:34 24 4
gpt4 key购买 nike

我正在寻找一种可以将两种颜色之间的距离准确表示为数字或其他内容的函数。

例如,我想要一个 HEX 值数组或 RGB 数组,并且我想在数组中为给定颜色找到最相似的颜色

例如。我将一个 RGB 值传递给一个函数,并返回数组中“最接近”的颜色

最佳答案

每种颜色都表示为十六进制代码中的一个元组。要确定接近匹配,您需要分别减去每个 RGB 分量。

例子:

Color 1: #112233 
Color 2: #122334
Color 3: #000000

Difference between color1 and color2: R=1, G=1 B=1 = 0x3
Difference between color3 and color1: R=11, G=22, B=33 = 0x66

So color 1 and color 2 are closer than
1 and 3.

编辑

所以你想要最接近的命名颜色?用每种颜色的十六进制值创建一个数组,迭代它并返回名称。像这样的东西;

function getColor($rgb)
{
// these are not the actual rgb values
$colors = array(BLUE =>0xFFEEBB, RED => 0x103ABD, GREEN => 0x123456);

$largestDiff = 0;
$closestColor = "";
foreach ($colors as $name => $rgbColor)
{
if (colorDiff($rgbColor,$rgb) > $largestDiff)
{
$largestDiff = colorDiff($rgbColor,$rgb);
$closestColor = $name;
}

}
return $closestColor;

}

function colorDiff($rgb1,$rgb2)
{
// do the math on each tuple
// could use bitwise operates more efficiently but just do strings for now.
$red1 = hexdec(substr($rgb1,0,2));
$green1 = hexdec(substr($rgb1,2,2));
$blue1 = hexdec(substr($rgb1,4,2));

$red2 = hexdec(substr($rgb2,0,2));
$green2 = hexdec(substr($rgb2,2,2));
$blue2 = hexdec(substr($rgb2,4,2));

return abs($red1 - $red2) + abs($green1 - $green2) + abs($blue1 - $blue2) ;

}

关于php - PHP 中颜色之间的 "Distance",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1633828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com