在PHP中对类似的十六进制代码进

时间:2012-12-06 16:16:17

标签: php colors hex

我有以下颜色代码:

  

f3f3f3
  f9f9f9

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

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

  

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

  

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

     

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

1 个答案:

答案 0 :(得分: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

,得到红色,绿色和蓝色的增量,以获得颜色距离。