【问题标题】:Triple HEX code to RGB三重 HEX 代码转 RGB
【发布时间】:2012-02-03 19:41:03
【问题描述】:

我在三重十六进制颜色代码转换为RGB颜色代码时遇到了麻烦。

到目前为止,我对 HEX 到 RGB 的了解是:

if(strlen($hex) == 3) {
        $color['r'] = hexdec(substr($hex, 0, 1) . $r);
        $color['g'] = hexdec(substr($hex, 1, 1) . $g);
        $color['b'] = hexdec(substr($hex, 2, 1) . $b);
    }

当我将 RGB 代码转换回 HEX 时,它是不同的。

例如:#FFF becomes 15, 15, 1515, 15, 15 is #0F0F0F

我也不确定将 RGB 转换回三重 HEX 代码。我的 RGB 转 HEX 代码如下所示:

$hex = str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
$hex.= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);

非常感谢任何帮助!提前致谢!

【问题讨论】:

  • 似乎“去掉填充物”会恢复原状?您需要提前知道要输出 3 还是 6:如果输出 6,则将每个组件缩放 16。有些浏览器可能不支持 3,所以我总是发出 6。
  • 这就是我将 RGB 恢复为 HEX 的方式,对吧?但是三重 HEX 代码中的错误 RGB 代码怎么办?
  • @pst 那应该是答案而不是评论?多花点功夫来解释该评论,您可以获得一些不错的声誉积分。

标签: php hex rgb


【解决方案1】:
function hex2rgb($hex)
{
    // Ensure we're working only with upper-case hex values,
    // toss out any extra characters.
    $hex = preg_replace('/[^A-F0-9]/', '', strtoupper($hex));

    // Convert 3-letter hex RGB codes into 6-letter hex RGB codes
    $hex_len = strlen($hex);
    if ($hex_len == 3) {
        $new_hex = '';
        for ($i = 0; $i < $hex_len; ++$i) {
            $new_hex .= $hex[$i].$hex[$i];
        }
        $hex = $new_hex;
    }

    // Calculate the RGB values
    $rgb['r'] = hexdec(substr($hex, 0, 2));
    $rgb['g'] = hexdec(substr($hex, 2, 2));
    $rgb['b'] = hexdec(substr($hex, 4, 2));

    return $rgb;
}

print_r(hex2rgb('#fff'));      // r: 255 g: 255 b: 255
print_r(hex2rgb('#AE9C00'));   // r: 174 g: 156 b: 0

【讨论】:

    【解决方案2】:

    您似乎需要以不同的方式处理三元组:#XYZ = #XXYYZZ。例如,#FFF 应该与 #FFFFFF 相同,或者是 (255, 255, 255),而不是 (15, 15, 15)。

    因此,一种方法是使用以下代码:

    if(strlen($hex) == 3) {
        $color['r'] = hexdec(substr($hex, 0, 1) . substr($hex, 0, 1));
        $color['g'] = hexdec(substr($hex, 1, 1) . substr($hex, 1, 1));
        $color['b'] = hexdec(substr($hex, 2, 1) . substr($hex, 2, 1));
    }
    

    请注意,我不包括 $r、$g 和 $b,因为我不知道您为什么要使用它们。

    【讨论】:

      猜你喜欢
      • 2015-11-02
      • 2013-03-28
      • 2011-04-17
      • 1970-01-01
      • 2018-02-25
      • 2013-04-03
      • 2016-08-11
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多