0

I want to get pixel color on raster coordinates like for example:

[0,0] - pixel in first row and first column (top left)

[0,1] - pixel in first row and second column and so on.

I'm loading my bitmap like so:

BitsPerPixel = FileInfo[28];
width = FileInfo[18] + (FileInfo[19] << 8);
height = FileInfo[22] + (FileInfo[23] << 8);
int PixelsOffset = FileInfo[10] + (FileInfo[11] << 8);
int size = ((width * BitsPerPixel + 31) / 32) * 4 * height;
Pixels.resize(size);
hFile.seekg(PixelsOffset, ios::beg);
hFile.read(reinterpret_cast<char*>(Pixels.data()), size);
hFile.close();

and my GetPixel function:

void BITMAPLOADER::GetPixel(int x, int y, unsigned char* pixel_color)
{
    y = height - y;
    const int RowLength = 4 * ((width * BitsPerPixel + 31) / 32);
    pixel_color[0] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8];
    pixel_color[1] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8 + 1];
    pixel_color[2] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8 + 2];
    pixel_color[3] = Pixels[RowLength * y * BitsPerPixel / 8 + x * BitsPerPixel / 8 + 3];
}

I know the data in bitmap are stored up side down, so I wanted to invert it using the y = height - y; but with this line I only get some values which even are not in the image data array. Without inverting the image I get some values which are in the array but they never correspond with the coords given. My bitmap can be 24-bit or 32-bit.

ProXicT
  • 1,903
  • 3
  • 22
  • 46

1 Answers1

0

For bit depth = 24, 3 bytes are stored. The padding is not done per pixel, only on each row:

const int bytesPerPixel = BitsPerPixel / 8;
const int align = 4;
const int RowLength = (width * bytesPerPixel + (align - 1)) & ~(align - 1);
...
pixel_color[0] = Pixels[RowLength * y + x * bytesPerPixel];
...
rpress
  • 462
  • 3
  • 6
  • Thanks, right now I wanted to post solution and I see your answer :) It's now working for me with following code: http://pastebin.com/MYHVuvZq Thank you for your answer anyway! Can you explain me please what does this: `(align - 1)) & ~(align - 1);`? – ProXicT May 27 '15 at 15:43
  • @ProXicT It is an old trick to round to the next power of two, if needed. `align` must be a power of two. There's no need for divisions/shifts in that case, the AND in conjunction with the NOT operation clears the lower bits. – rpress May 27 '15 at 16:13
  • Oh, thanks, but I still don't know why it needs to be there. Why don't you just put 16 in the const initialization? – ProXicT May 27 '15 at 16:15