在PHP中将类似的十六进制代码分组

7

我有以下颜色代码:

f3f3f3
f9f9f9

这两个颜色代码在视觉上非常相似。我应该如何将它们归为一种颜色或删除其中一个?

如果尝试使用base_convert($hex, 16, 10)并获取值之间的差异,问题是某些颜色在int值上相似但视觉上实际上不同。例如:

#484848 = 4737096 (灰色)
#4878a8 = 4749480 (蓝色) - 视觉上有很大的差别,但是作为整数值的差异很小

#183030 = 1585200 (灰色)
#181818 = 1579032 (灰色) - 两者都可以

#4878a8 = 4749480 (蓝色)
#a81818 = 11016216 (红色) - 差异巨大,无论从视觉上还是整数值上来看


1
转换为RGB值可以更准确地确定颜色的接近程度,我认为。 - cryptic ツ
1个回答

4

使用hexdec函数将十六进制颜色代码转换为其RGB等效代码。例如(来自hexdec页面的示例):

<?php
/**
 * Convert a hexa decimal color code to its RGB equivalent
 *
 * @param string $hexStr (hexadecimal color value)
 * @param boolean $returnAsString (if set true, returns the value separated by the separator character. Otherwise returns associative array)
 * @param string $seperator (to separate RGB values. Applicable only if second parameter is true.)
 * @return array or string (depending on second parameter. Returns False if invalid hex color value)
 */                                                                                                 
function hex2RGB($hexStr, $returnAsString = false, $seperator = ',') {
    $hexStr = preg_replace("/[^0-9A-Fa-f]/", '', $hexStr); // Gets a proper hex string
    $rgbArray = array();
    if (strlen($hexStr) == 6) { //If a proper hex code, convert using bitwise operation. No overhead... faster
        $colorVal = hexdec($hexStr);
        $rgbArray['red'] = 0xFF & ($colorVal >> 0x10);
        $rgbArray['green'] = 0xFF & ($colorVal >> 0x8);
        $rgbArray['blue'] = 0xFF & $colorVal;
    } elseif (strlen($hexStr) == 3) { //if shorthand notation, need some string manipulations
        $rgbArray['red'] = hexdec(str_repeat(substr($hexStr, 0, 1), 2));
        $rgbArray['green'] = hexdec(str_repeat(substr($hexStr, 1, 1), 2));
        $rgbArray['blue'] = hexdec(str_repeat(substr($hexStr, 2, 1), 2));
    } else {
        return false; //Invalid hex color code
    }
    return $returnAsString ? implode($seperator, $rgbArray) : $rgbArray; // returns the rgb string or the associative array
} ?>

输出:

hex2RGB("#FF0") -> array( red =>255, green => 255, blue => 0)
hex2RGB("#FFFF00) -> Same as above
hex2RGB("#FF0", true) -> 255,255,0
hex2RGB("#FF0", true, ":") -> 255:255:0

然后,获取红色、绿色和蓝色差值,以获取颜色距离。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接