是否可以根据定义的“中心值”检查特定的十六进制颜色是否更接近FFF或000?
我想根据#888检查颜色是否更接近#FFF或#000。所以如果我检查#EFEFEF,它应该返回#FFF,如果我尝试#878787,它应该返回#000。
如何才能做到这一点?我不确定要在谷歌上搜索什么.
提前感谢
发布于 2012-05-11 20:38:06
解决问题的最简单方法是使用颜色的灰度值计算颜色之间的距离(还有其他方法,但这很简单)。所以就像这样:
// 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);输出为:
string(7) "#FFFFFF"
string(7) "#000000"发布于 2012-05-11 20:22:47
您可以将颜色转换为数字:
$color_num = hexdec(substr($color, 1)); // skip the initial #然后将它们与0x0或0xffffff进行比较。
您还可以将它们分解为R、G和B,并进行三次比较;然后对它们进行平均?不确定你想要这个东西有多精确:)
发布于 2012-05-11 20:25:40
您可以执行类似以下操作:
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。
https://stackoverflow.com/questions/10551232
复制相似问题