I am trying to make coder/decoder in Java so I could store RGB value in Hex format. I have coder like this:

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

and decoder like this:

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

Implementation of decodeColor() function is:

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);
}

When I run test program, I get this output:

  • initial values are new RGB(15, 255, 45)

<\label ... color="#fff2d">...</label>

RGB {15, 255, 45}

  • initial values are RGB(15, 0, 45)

<\label ... color="#f02d">...</label>

RGB {0, 240, 45}

So, in some cases it returns correct result, but in other its totally messed up. Why is that?

有帮助吗?

解决方案

Because #rrggbb always requires 2 hex digits per color component.

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

Color c = Color.decode(s);

其他提示

Integer intval = Integer.decode(attribute);

Here, the string attribute starts with a #, but it should start with 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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top