Search code examples
image-processingpixelbmp

Can anyone please explain what RowSize and PixelArraySize mean in BMP file format?


I was writing a code for reading a BMP Image files, and I couldn't understand what RowSize and PixelArraySize mean or their operation, are these two formulas used for padding the row to a multiple of 4 bytes? Can anyone help me to understand this? Thanks a lot!

enter image description here

enter image description here


Solution

  • As is explained in the picture just below the formula, RowSize represents a single image row size in bytes, rounded (padded) to a nearest multiple of 4. This padding is often applied for performance reasons (memory alignment).

    The formula shows 2 ways to calculate RowSize, padded to 4 bytes:

    1. ceil(BitsPerPixel * ImageWidth / 32) * 4 - take row size in bits, divide by 32 (i.e. 4 bytes), round up, then multiply by 4 to get the number in bytes

    2. floor((BitsPerPixel * ImageWidth + 31) / 32) * 4 - take row size in bits, add 31, divide by 32 (i.e. 4 bytes), round down, then multiply by 4 to get the number in bytes

    You can see that the two ways are equivalent.

    Version 2 is often preferred because rounding down in integer arithmetic happens implicitly:

    int BitsPerPixel, ImageWidth;
    . . .
    int RowSize = ((BitsPerPixel * ImageWidth + 31) / 32) * 4; // Voila.
    

    Now, PixelArraySize is just RowSize times the number of rows.