创建一个自定义的getColor(byte r, byte g, byte b)方法

3
我有一个简单的字节数组,我想从中提取颜色。我的计划是使用三位红色、三位绿色和两位蓝色。8位。
我认为这些颜色是正确的:
如果我错了,请纠正我。
 byte[] colours = new byte[256]; //256 different colours, 8 * 8 * 4 
                                 //(3 bits(red) + 3 bits(green) + 2 bits(blue)
 int index = 0;
 for(byte r = 0; r < 8; r++){ 
    for(byte g = 0; g < 8; g++){
       for(byte b = 0; b < 4; b++){
           byte rr = (r & 255);
           byte gg = (g & 255);
           byte bb = (b & 255);
           colours[index++] = (rr << 5 | gg << 2 | bb);   
       }
   }
}

我的目标是让getColor(byte r, byte g, byte b)看起来像这样:

public static byte getColor(byte r, byte g, byte b){
    return colours[return the right color using r g b];
}

但我不知道该怎么做,这就是我需要帮助的地方。

如果可能的话,我宁愿不使用Color类。

其他信息: 我正在使用BufferedImage.TYPE.BYTE.INDEXED进行绘制。

如果我的英语不好,请原谅 :)

编辑 已修正错误


这行代码的目的是什么? colours[(rr << 5 | gg << 2 | bb)]; - ogzd
你的 getColor 不应该是 void,因为它返回一个值。 - afsantos
@ogzd 这是一种旧技术,使用较大值的各个位来存储每个通道。在处理像Mode 13h这样的事物时,您曾经在旧的ASM代码中看到过它。 - Jason Sperske
int index是什么?它从未被使用过。 - mjshaw
colours[(rr << 5 | gg << 2 | bb)]; 这行代码指定了数组 colours 中的一个位置,但没有对其进行任何操作。@ogzd 是正确的,这看起来很奇怪。 - mjshaw
显示剩余2条评论
1个回答

0

Java中的byte是有符号的,用2的补码表示,所以你不能只是这样移位。
从128开始,你必须反转比特模式,使用负值。

byte[] colours = new byte[256];

for(int i = 0; i < colours.length; i++){ 
    colours[i] = (byte) (i < 128 ? i : i - 256);
}

你的方法应该是这样的:

public static byte getColour(byte r, byte g, byte b)
        throws InvalidColourException {
    if (r >= 8 || r < 0)
        throw new InvalidColourException("Red is out of range.");
    if (g >= 8 || g < 0)
        throw new InvalidColourException("Green is out of range.");
    if (b >= 4 || b < 0)
        throw new InvalidColourException("Blue is out of range.");
    int i = (int) r << 5;
    i += (int) g << 2;
    i += (int) b;
    return colours[i];
}

虽然你可以将所有内容缩减为一个方法,并且放弃数组:

public static byte getColour(byte r, byte g, byte b)
        throws InvalidColourException {
    if (r >= 8 || r < 0)
        throw new InvalidColourException("Red is out of range.");
    if (g >= 8 || g < 0)
        throw new InvalidColourException("Green is out of range.");
    if (b >= 4 || b < 0)
        throw new InvalidColourException("Blue is out of range.");
    int c = (int) r << 5;
    c += (int) g << 2;
    c += (int) b;
    return (byte) c;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接