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);
Domanda
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:
<\label ... color="#fff2d">...</label>
RGB {15, 255, 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?
Soluzione
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);
Altri suggerimenti
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);
}