2013-02-08 55 views
0

我正在開發一個Java EE應用程序,其中有一個包含某些產品的「項目」表以及一個用於設置其顏色的字段。16位轉換的相對8位顏色

問題:用戶從包含16或128種顏色的調色板中選擇顏色。我存儲顏色爲一個字節(8位顏色),我需要能夠爲RGB顏色/整數轉換成它的8位等效,反之亦然,如:

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

我有什麼嘗試到目前爲止:

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

當我循環通過顏色值0到255,我得到一個單一的色調變化。

+0

你的代碼似乎是無效的,在的getColor你不回色 – AlexWien 2013-02-08 15:09:09

回答

3

因此,在8位色彩:

111 111 11 
red grn bl 

隨着紅色和綠色的8倍不同的值:藍色

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/

+0

非常感謝你,這正是我想要的。 – 2013-02-08 16:07:53