A while ago I needed an estimate for [WayBack] How to calculate bitmap size? – Stack Overflow, which does an accurate calculation for the size of the pixel storage (i.e. without headers):
pixelStorageSize = (( width*bitsPerPixel + 31) / 32) * 4 * height
Here:
- 4 is the number of bytes per quad-byte as bitmaps are stored with pixel lines aligned on quad-byte boundaries
- 32 is the bits per quad-byte
- 31 helps to round up to the quad-word boundary
It was derived from [WayBack] Capturing an Image – Windows applications | Microsoft Docs and shorthand for what is explained at [WayBack] BMP file format: Pixel storage – Wikipedia
The bits representing the bitmap pixels are packed in rows. The size of each row is rounded up to a multiple of 4 bytes (a 32-bit DWORD) by padding.
For images with height above 1, multiple padded rows are stored consecutively, forming a Pixel Array.
The total number of bytes necessary to store one row of pixels can be calculated as:
- {\displaystyle {\text{RowSize}}=\left\lceil {\frac {{\text{BitsPerPixel}}\cdot {\text{ImageWidth}}}{32}}\right\rceil \cdot 4=\left\lfloor {\frac {{\text{BitsPerPixel}}\cdot {\text{ImageWidth}}+31}{32}}\right\rfloor \cdot 4,}
- ImageWidth is expressed in pixels, note the special parentheses.
The total amount of bytes necessary to store an array of pixels in an n bits per pixel (bpp) image, with 2ncolors, can be calculated by accounting for the effect of rounding up the size of each row to a multiple of 4 bytes, as follows:
- PixelArraySize = RowSize · |ImageHeight|
- ImageHeight is expressed in pixels. The absolute value is necessary because ImageHeight can be negative.
I think I needed this to estimate how many bitmaps would fit in
[WayBack] Virtual address space – Wikipedia, which on 32-bit Windows by default is limited to 2 GiB, and can be extended to 3 GIB by enabling the IMAGE_FILE_LARGE_ADDRESS_AWARE
executable header flag.
This flag imposes the risk of many libraries and DLLs to fail because they do not get the pointer math right. You often do not have control of future versions of DLLs being loaded in your process space and their risks, so do not ever use that flag.
–jeroen