首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算色差

计算色差
EN

Stack Overflow用户
提问于 2012-05-11 20:20:20
回答 4查看 136关注 0票数 5

是否可以根据定义的“中心值”检查特定的十六进制颜色是否更接近FFF或000?

我想根据#888检查颜色是否更接近#FFF或#000。所以如果我检查#EFEFEF,它应该返回#FFF,如果我尝试#878787,它应该返回#000。

如何才能做到这一点?我不确定要在谷歌上搜索什么.

提前感谢

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-05-11 20:38:06

解决问题的最简单方法是使用颜色的灰度值计算颜色之间的距离(还有其他方法,但这很简单)。所以就像这样:

代码语言:javascript
复制
// returns a distance between two colors by comparing each component
// using average of the RGB components, eg. a grayscale value
function color_distance($a, $b)
{
    $decA = hexdec(substr($a, 1));
    $decB = hexdec(substr($a, 1));
    $avgA = (($decA & 0xFF) + (($decA >> 8) & 0xFF) + (($decA >> 16) & 0xFF)) / 3;
    $avgB = (($decB & 0xFF) + (($decB >> 8) & 0xFF) + (($decB >> 16) & 0xFF)) / 3;
    return abs($avgA - $avgB);
}

// I am going to leave the naming of the function to you ;)
// How this works is that it'll return $minColor if $color is closer to $refColorMin
// and $maxColor if $color is closer to $refColorMax
// all colors should be passed in format #RRGGBB
function foo($color, $refColorMin, $refColorMax, $minColor, $maxColor)
{
    $distMin = color_distance($color, $refColorMin);
    $distMax = color_distance($color, $refColorMax);
    return ($distMin < $distMax) ? $minColor : $maxColor;
}

// Example usage to answer your original question:
$colorA = foo('#EFEFEF', '#888888', '#FFFFFF', '#000000', '#FFFFFF');
$colorA = foo('#898989', '#888888', '#FFFFFF', '#000000', '#FFFFFF');
// Check the values
var_dump($colorA, $colorB);

输出为:

代码语言:javascript
复制
string(7) "#FFFFFF"
string(7) "#000000"
票数 2
EN

Stack Overflow用户

发布于 2012-05-11 20:22:47

您可以将颜色转换为数字:

代码语言:javascript
复制
$color_num = hexdec(substr($color, 1)); // skip the initial #

然后将它们与0x00xffffff进行比较。

您还可以将它们分解为R、G和B,并进行三次比较;然后对它们进行平均?不确定你想要这个东西有多精确:)

票数 3
EN

Stack Overflow用户

发布于 2012-05-11 20:25:40

您可以执行类似以下操作:

代码语言:javascript
复制
function hex2rgb($hex) {
   $hex = str_replace("#", "", $hex);

   if(strlen($hex) == 3) {
      $r = hexdec(substr($hex,0,1).substr($hex,0,1));
      $g = hexdec(substr($hex,1,1).substr($hex,1,1));
      $b = hexdec(substr($hex,2,1).substr($hex,2,1));
   } else {
      $r = hexdec(substr($hex,0,2));
      $g = hexdec(substr($hex,2,2));
      $b = hexdec(substr($hex,4,2));
   }
   $rgb = array($r, $g, $b);
   //return implode(",", $rgb); // returns the rgb values separated by commas
   return $rgb; // returns an array with the rgb values
}

$rgb = hex2rgb("#cc0");

由此,您可以获取$rgb的值,并查看它们的值是否平均大于或小于122.5。如果它大于122.5,你将更接近#FFFFFF,低于122.5,你将更接近#000000。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10551232

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档