【问题标题】:Group similar hex codes in PHP在 PHP 中对类似的十六进制代码进行分组
【发布时间】:2012-11-24 17:33:17
【问题描述】:

我有以下颜色代码:

f3f3f3
f9f9f9

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

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

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

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

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

【问题讨论】:

  • 转换为 RGB 值可以让您更准确地确定我认为的颜色的接近程度。

标签: php colors hex


【解决方案1】:

使用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

然后,获取红色、绿色和蓝色的增量,以获取颜色距离。

【讨论】:

    猜你喜欢
    • 2011-03-02
    • 2011-06-10
    • 2013-12-27
    • 2021-02-28
    • 2012-05-29
    • 2019-01-01
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多