public void printPixelARGB(int开发者_Go百科 pixel){
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
System.out.println("ARGB : " + alpha + ", " + red + ", " + green + ", " + blue);
}
I've found Java syntax to show the RGB value for each pixel of an image, but I'm a little confused about that method. Can you help me by explaining that method?
0xff
? what is that? Also, what does (pixel>>24) & 0xff
mean? Thanks in advance.
pixel is an int
an int has 4 bytes in it, each byte has 8 bits in it
as an example
0xA3 0x41 0x28 0x76
is an example pixel (1 int, with 4 bytes in it and 32 bits)
Now packed in this pixel is information about the transparency (A) the red, green and blue components.
The transparency is the first byte (0xA3) then red (0x41) then green (0x28) then blue (0x76)
so to get just the red part out, you shift to the right by 16 bits, which gives
0x00 0x00 0xA3 0x41
now the red is the right most spot, but you got that transparency byte there, which isn't good, so you have to remove it
doing & 0xFF, is really
0xA341 & 0x00FF
which means you and each bit, so the bits of A3 are anded with 00 which gives 0, and the bits of 41 are anded with FF which since FF is all ones, gives you the original value, which is 41
so red is
0x00 0x00 0x00 0x41
So this code, is pulling out each component by itself from an integer.
0xff
is hexadecimal (another system of counting based on 16, rather than 10), it means 255. >>
and &
are bitwise right shift and bitwise AND, respectively (see the wikipedia article).
Colors are often dealt with in hexadecimal, as RGB values are represented in values from 0 to 255 (e.g. 0x00 to 0xff), as seen in HTML color codes (e.g. #FFFFFF).
The program that stores pixels uses some optimization around int
being primitive type.
I suspect, that somewhere in your program there is a definition like that:
int screen[1024][726];
From object-oriented point of view this is complete heresy, but sometimes performance does matter.
Here is how pixel would be represented as a full-fledged Java object:
class Pixel
{
byte alpha;
byte red;
byte green;
byte blue;
}
But nothing comes for free, and having need to update many objects on each screen refresh does add up. That's why they are stored as very fast int
s and when you need to access the contents, you need to jump through some bit manipulation hoops.
>>
and & 0xff
come handy here as they allow to access particular bits at some predefined positions and convert them to values that represent the color intensity.
As you can see, if you had dealt with Pixel objects that job would be much easier.
精彩评论