quot;Distancequot; between colours in PHP(“距离PHP中的颜色之间)
问题描述
我正在寻找一种可以将两种颜色之间的距离准确地表示为数字或其他东西的函数.
I'm looking for a function that can accurately represent the distance between two colours as a number or something.
例如,我希望有一个十六进制值或 RGB 数组的数组,并且我想在给定颜色的数组中找到最相似的颜色
For example I am looking to have an array of HEX values or RGB arrays and I want to find the most similar colour in the array for a given colour
例如.我向函数传递一个 RGB 值,并返回数组中最接近"的颜色
eg. I pass a function a RGB value and the 'closest' colour in the array is returned
推荐答案
每种颜色在 HEX 代码中都表示为一个元组.要确定接近匹配,您需要分别减去每个 RGB 分量.
Each color is represented as a tuple in the HEX code. To determine close matches you need to subtract each RGB component separately.
示例:
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.
编辑
所以你想要最接近的命名颜色?使用每种颜色的十六进制值创建一个数组,迭代它并返回名称.像这样;
So you want the closest named color? Create an array with the hex values of each color, iterate it and return the name. Something like this;
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中的颜色之间
基础教程推荐
- PHP 守护进程/worker 环境 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01