简体   繁体   中英

creating a custom getColor(byte r, byte g, byte b) method

i have a simple byte array that i want to take colours from. My plan was to have three bits from red, three bits for green, and two bits for blue. 8-bit.

I think the colours are right:

Please correct me if i'm wrong,

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

My goal is to make a getColor(byte r, byte g, byte b) like

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

But i don't know how. Here's where i need help.

I would like to rather not use the Color class if it's possible.

Other information: I'm using a BufferedImage.TYPE.BYTE.INDEXED to paint on.

Sorry if my english is bad :)

EDIT Fixed where it was wrong

Java's byte is signed, represented in 2's complement, so you can't just shift that way.
From 128 on, you have to reverse the bit pattern, using negative values.

byte[] colours = new byte[256];

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

Your method should be something along the lines of:

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

Although, you could shrink it all to a single method, and discard the array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM