php - 在 PHP 中对相似的十六进制代码进行分组

标签 php colors hex

我有以下颜色代码:

f3f3f3
f9f9f9

从视觉上看,这两种颜色代码很相似。如何将它们组合成一种颜色,或删除其中一个?

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

#484848 = 4737096 (grey)
#4878a8 = 4749480 (blue) - visually there is a huge difference, but as int value the difference is small

#183030 = 1585200 (greyish)
#181818 = 1579032 (greyish) - both ways is fine

#4878a8 = 4749480 (blue)
#a81818 = 11016216 (red) - the difference is huge, both visual and as int value

最佳答案

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

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

关于php - 在 PHP 中对相似的十六进制代码进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13747841/

相关文章:

colors - vim colorchem 显示不正确的颜色

c# - Int64.MinValue 的十六进制文字

php - 如何在包含的 PHP 页面处理/加载时显示 Prelaoder/加载动画/gif/百分比?

php - 为什么订单总计未显示在 Magento 报告和最后 5 个订单网格中?

php - MySQL 表中的 Twilio 数字数组 - PHP

python - 当我不知 Prop 体编码时如何解码数据

php - PHP二进制到十六进制,前导零

php - 使用 Nexmo PHP Laravel 进行 Web 浏览器音频通话

带有 NM_CUSTOMDRAW 的 ListView 项目闪烁

iphone - 如何从十六进制值转换为 UIColor?