Relative 8-bit color 16-bit conversion

I am working on a Java EE application in which I have a “items” table that will contain some products and a field to set its color.

Problem: user selects a color from a palette containing 16 or possibly 128 colors. I save the color as a byte (8-bit color), and I need to be able to convert the RGB color / integer to its 8-bit equivalent and vice versa, for example:

White:  0xFF(0b 111 111 11) to -1     or (255,255,255)
Red:    0x10(0b 111 000 00) to -65536 or (255, 0, 0  )

What I have tried so far:

void setColor(Color color){
   short sColor =  (color.getRGB() >> 16) & 0xFF) >> 8
                 | (color.getRGB() >> 8) & 0xFF) >> 8
                 | (color.getRGB() >> 0) & 0xFF) >> 8;
   }

Color getColor(short sColor){
   Color rgb = new Color(
                        /*red:*/  (sColor & 0xF) << 16, 
                        /*gree:*/ (sColor & 0xF) << 8, 
                        /*blue*/  (sColor & 0xF) << 0));
}
/* or */

Color getColor(short sColor){
   Color rgb = new Color((sColor << 8) + sColor));
}

When I iterate over color values ​​from 0 to 255, I get one hue.

0
source share
1 answer

So, in 8-bit color:

111 111 11
red grn bl

?

With 8 different values ​​for red and green:

0 (0)
1 (36)
2 (72)
3 (109)
4 (145)
5 (182)
6 (218)
7 (255)

4 .

:

public static Color fromByte(byte b) {
    int red = (int) Math.round(((b & 0xE0) >>> 5) / 7.0 * 255.0);
    int green = (int) Math.round(((b & 0x1C) >>> 2) / 7.0 * 255.0);
    int blue = (int) Math.round((b & 0x03) / 3.0 * 255.0);
    return new Color(red, green, blue);
}

public static byte fromColor(Color color) {
    int red = color.getRed();
    int green = color.getGreen();
    int blue = color.getBlue();

    return (byte) (((int) Math.round(red / 255.0 * 7.0) << 5) |
                ((int) Math.round(green / 255.0 * 7.0) << 2) |
                ((int) Math.round(blue / 255.0 * 3.0)));
}

http://jsfiddle.net/e3TsR/

+3

All Articles