I understand RGB when R, G and B are separate 0-264 values, but how does the scale/coloring work when it’s expressed as one number?
Like when you use setRGB on a BufferedImage. It only takes one RGB value… how does that work?
I understand RGB when R, G and B are separate 0-264 values, but how does the scale/coloring work when it’s expressed as one number?
Like when you use setRGB on a BufferedImage. It only takes one RGB value… how does that work?
RGB ranges 0-255. The setRGB method takes int[] as parameter, each one representing color of one pixel. To make it easy, write it in hexa like 0xff567c. That’s single value concating value of R, G and B together.
The values go from 0 to 255 (not 264) because it uses 1 byte for each color channel. Since setRGB takes an integer and an integer has 4 bytes, each byte represents each color channel (the 4th byte is for alpha and it is the leftmost byte, however it may or may not be used depending on the type of the BufferedImage). An example:
ARGB = 255 255 255 255
Hex = 0xffffffff
Binary = 11111111 11111111 11111111 11111111
ARGB = 50 50 50 50
Hex = 0x32323232
Binary = 00110010 00110010 00110010 00110010
EDIT: @Rebirth, the OP is talking about the 3-argument setRGB(int x, int y, int rgb)
Oops I meant 255 (256 colors/value DUH). Dumb mistake…
Thanks for the explanation!
I know the OP didn’t request it, but I thought I’d share since I’ve been tinkering with this as well. This is what I use to (I think) convert between an ARGB int and separate ARGB values. I’ve tested the color returned by toARGB() and it works, but I haven’t tested the color returned by toAWT() except by printing it and seeing that I get the same ARGB values.
public static int toARGB(int r, int g, int b, int a)
{
int argb = a;
argb = (argb << 8) + r;
argb = (argb << 8) + g;
argb = (argb << 8) + b;
return argb;
}
public static Color toAWT(int rgbInt)
{
int r, g, b, a;
b = rgbInt & 255;
g = (rgbInt >> 8) & 255;
r = (rgbInt >> 16) & 255;
a = (rgbInt >> 24) & 255;
return new Color(r, g, b, a);
}
Ewww lets change that toARGB into a one liner shall we please?
public static int toARGB(int a, int r, int g, int b) {
return (a << 24) + (r << 16) + (g << 8) + b;
}
And that toAWT method is buggy because using >> will keep the negative sign for all of them if alpha value is greater than 127:
public static Color toAWT(int rgb) {
int a = (rgb >> 24) & 0xff;
int r = (rgb >> 16) & 0xff;
int g = (rgb >> 8) & 0xff;
int b = rgb & 0xff;
return new Color(r,g,b,a);
}
Oops, thanks for the fix and the optimization ;D
Why don’t you just do
new Color(rgba, hasAlpha);
The color’s value is stored as an integer in the Color class anyways… it doesn’t make sense to strip out the color channels just so they can be packed together into an integer again