【问题标题】:How to code and decode RGB to Hex如何将 RGB 编码和解码为十六进制
【发布时间】:2013-09-25 16:45:47
【问题描述】:

我正在尝试用 Java 制作编码器/解码器,以便可以以十六进制格式存储 RGB 值。我有这样的编码器:

System.out.println("#" + Integer.toHexString(label.getColor().getRed())
    + Integer.toHexString(label.getColor().getGreen())
    + Integer.toHexString(label.getColor().getBlue()));

和这样的解码器:

System.out.println(decodeColor("#"
    + Integer.toHexString(label.getColor().getRed())
    + Integer.toHexString(label.getColor().getGreen())
    + Integer.toHexString(label.getColor().getBlue())));

decodeColor()函数的实现是:

private RGB decodeColor(String attribute) {
    Integer intval = Integer.decode(attribute);
    int i = intval.intValue();
    return new RGB((i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
}

当我运行测试程序时,我得到这个输出:

  • 初始值为新的 RGB(15,255,45)

...

RGB {15、255、45}

  • 初始值为 RGB(15, 0, 45)

...

RGB {0、240、45}

因此,在某些情况下它会返回正确的结果,但在其他情况下则完全搞砸了。这是为什么呢?

【问题讨论】:

标签: java hex rgb data-conversion


【解决方案1】:
Integer intval = Integer.decode(attribute);

这里,字符串attribute# 开头,但它应该以0x 开头。

private RGB decodeColor(String attribute) {
    String hexValue = attribute.replace("#", "0x");

    int i = Integer.decode(hexValue).intValue();
    return new RGB((i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF);
}

【讨论】:

    【解决方案2】:

    因为 #rrggbb 每个颜色分量总是需要 2 个十六进制数字。

    String s = String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue());
    
    Color c = Color.decode(s);
    

    【讨论】:

      猜你喜欢
      • 2020-06-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 1970-01-01
      • 2021-03-22
      • 2018-10-13
      • 1970-01-01
      相关资源
      最近更新 更多