anoneironaut
anoneironaut

Reputation: 1868

Why is the bitmap size calculated this way?

I was reading a Window example related to capturing an image. The article is located at http://msdn.microsoft.com/en-us/library/dd183402(v=vs.85).aspx. One thing that stuck out to me was the calculation of the bitmap size. It was this:

 DWORD dwBmpSize = ((bmpScreen.bmWidth * bi.biBitCount + 31) / 32) * 4 * bmpScreen.bmHeight;

I expected it to be something more like this:

 DWORD dwBmpSize = bmpScreen.bmWidth  * bmpScreen.bmHeight * bi.biBitCount / 8;

Would anyone mind explaining the point of the former?

Thanks!

Upvotes: 1

Views: 240

Answers (1)

AnT stands with Russia
AnT stands with Russia

Reputation: 320747

Bitmap is represented by a sequence of horizontal scan lines. The smallest indivisible unit of that representation is a 32-bit word. These words are never shared between scan lines, meaning that if the last word in a scan line is not completely used, it is left that way (most likely with garbage values in unused bits). And the next scan line will begin with a new 32-bit word. For example, if your bitmap is only 1 pixel wide, it will still use a full 32-bit word to represent each and every bitmap line.

This is why the above formula begins with calculating how many 32-bit words is necessary to represent one scan line of the bitmap. This is exactly what the ... + 31) / 32 trick does. In general, in unsigned arithmetic (A + B - 1) / B will evaluate to A divided by B with rounding up. Thus, the ((bmpScreen.bmWidth * bi.biBitCount + 31) / 32 part tells you how many 32-bit words you need to represent one line of the bitmap. Then it is multiplied by 4, telling you how many 8-bit bytes you need to represent one line of the bitmap.

Finally, multiplying it by bmpScreen.bmHeight gives you the total number of 8-bit bytes for the entire bitmap.

Upvotes: 2

Related Questions