Java 创建自定义getColor(字节r、字节g、字节b)方法
我有一个简单的字节数组,我想从中获取颜色。我的计划是用红色的三位,绿色的三位,蓝色的两位。8位 我认为颜色是正确的: 如果我错了,请纠正我Java 创建自定义getColor(字节r、字节g、字节b)方法,java,colors,byte,rgb,8-bit,Java,Colors,Byte,Rgb,8 Bit,我有一个简单的字节数组,我想从中获取颜色。我的计划是用红色的三位,绿色的三位,蓝色的两位。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;
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);
}
}
}
但我不知道怎么做。这是我需要帮助的地方
如果可能的话,我宁愿不使用颜色类
其他资料:
我正在使用BuffereImage.TYPE.BYTE.INDEXED进行绘制
对不起,如果我的英语不好:)
编辑
修正了错误的地方Java的
字节
是有符号的,用2的补码表示,所以不能这样移位。从128开始,必须使用负值反转位模式
byte[] colours = new byte[256];
for(int i = 0; i < colours.length; i++){
colours[i] = (byte) (i < 128 ? i : i - 256);
}
byte[]colors=新字节[256];
对于(int i=0;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 i = (int) r << 5;
i += (int) g << 2;
i += (int) b;
return colours[i];
}
公共静态字节getcolor(字节r、字节g、字节b)
抛出InvalidColor异常{
如果(r>=8 | | r<0)
抛出新的InvalidColorException(“红色超出范围”);
如果(g>=8 | | g<0)
抛出新的InvalidColorException(“绿色超出范围”);
如果(b>=4 | | b<0)
抛出新的InvalidColorException(“蓝色超出范围”);
int i=(int)r=8 | | g<0)
抛出新的InvalidColorException(“绿色超出范围”);
如果(b>=4 | | b<0)
抛出新的InvalidColorException(“蓝色超出范围”);
int c=(int)rcolors[(rr你的getColor
不应该是void
,因为它返回一个值。@ogzd这是一种古老的技术,使用较大值的单个位来存储每个通道。在处理诸如模式13h之类的事情时,你经常在旧的ASM代码中看到这一点,int index
?它从不使用。colors[(rr
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;
}