7

我有以下颜色代码:

f3f3f3
f9f9f9

在视觉上,这两种颜色代码是相似的。如何将它们分组为一种颜色,或删除其中一种?

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

#484848 = 4737096(灰色)
#4878a8 = 4749480(蓝色) - 视觉上存在巨大差异,但作为 int 值差异很小

#183030 = 1585200(灰色)
#181818 = 1579032(灰色)- 两种方式都可以

#4878a8 = 4749480(蓝色)
#a81818 = 11016216(红色) - 差异很大,无论是视觉还是 int 值

4

1 回答 1

4

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

<?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

比,得到红色、绿色和蓝色的增量,得到颜色距离。

于 2012-12-06T16:21:32.073 回答