【问题标题】:creating a custom getColor(byte r, byte g, byte b) method创建自定义 getColor(byte r, byte g, byte b) 方法
【发布时间】:2013-02-11 04:15:54
【问题描述】:

我有一个简单的字节数组,我想从中获取颜色。我的计划是三个位来自红色,三个位为绿色,两个位为蓝色。 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 &lt;&lt; 5 | gg &lt;&lt; 2 | bb)];这条线的目的是什么?
  • 你的getColor 不应该是void,因为它会返回一个值。
  • @ogzd 这是一种古老的技术,使用较大值的各个位来存储每个通道。在处理模式 13h 之类的事情时,您曾经在旧 ASM 代码中看到这一点
  • 什么是int index?它从未使用过。
  • colours[(rr &lt;&lt; 5 | gg &lt;&lt; 2 | bb)]; 在数组 colours 中命名一个位置,然后什么也不做。 @ogzd 是对的,看起来很奇怪。

标签: java colors byte rgb 8-bit


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2010-12-06
    • 2015-06-07
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多