1
votes

Get RGB Channels From Pixel Value Without Any Library
I`m trying to get the RGB channels of each pixel that I read from an image. I use getchar by reading each byte from the image. so after a little search I did on the web I found the on BMP for example the colors data start after the 36 byte, I know that each channle is 8 bit and the whole RGB is a 8 bit of red, 8 bit of green and 8 bit of blue. my question is how I extract them from a pixel value?
for example:

pixel = getchar(image);

what can I do to extract those channels? In addition I saw this example on JAVA but dont know how to implement it on C++ :

int rgb[] = new int[] {
(argb >> 16) & 0xff, //red
(argb >>  8) & 0xff, //green
(argb      ) & 0xff  //blue
};

I guess that argb is the "pixel" var I mentioned before.
Thanks.

2
Just look up "bmp file reading". There isn't anything remotely special about it. - Pubby

2 Answers

1
votes

Assuming that it's encoded as ABGR and you have one integer value per pixel, this should do the trick:

int r = color & 0xff;
int g = (color >> 8) & 0xff;
int b = (color >> 16) & 0xff;
int a = (color >> 24) & 0xff;
0
votes

When reading single bytes it depends on the endianness of the format. Since there are two possible ways this is of course always inconsistent so I'll write both ways, with the reading done as a pseudo-function:

RGBA:

int r = readByte();
int g = readByte();
int b = readByte();
int a = readByte();

ABGR:

int a = readByte();
int b = readByte();
int g = readByte();
int r = readByte();

How it's encoded depends on how your file format is laid out. I've also seen BGRA and ARGB orders and planar RGB (each channel is a separate buffer of width x height bytes).

It looks like wikipedia has a pretty good overview on what BMP files look like: http://en.wikipedia.org/wiki/BMP_file_format

Since it seems to be a bit more complicated I'd strongly suggest using a library for this instead of rolling your own.