簡體   English   中英

創建自定義getColor(字節r,字節g,字節b)方法

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

我有一個簡單的字節數組,我想從中獲取顏色。 我的計划是紅色有三位,綠色有三位,藍色有兩位。 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(字節r,字節g,字節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進行繪制。

對不起,如果我的英語不好:)

編輯修正了錯誤的地方

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM