c++bitmapmsdnbitmapfactory

Are bitmaps supposed to be 2-byte or 4-byte aligned?


MSDN documentation seems to contradict itself:

Here it says:

For uncompressed RGB formats, the minimum stride is always the image width in bytes, rounded up to the nearest DWORD.

While here it says:

The number of bytes in each scan line. This value must be divisible by 2, because the system assumes that the bit values of a bitmap form an array that is word aligned.

So sometimes MSDN wants a 4-byte aligned stride and sometimes it wants a 2-byte aligned stride. Which is right?

To be more specific, when saving a bitmap file should I use a 4-byte stride or a 2-byte stride?


Solution

  • The first quote is accurate. The second dates back to the 16-bit version of Windows and did not get edited as it should have. Not entirely unusual, GDI32 docs have had a fair amount of mistakes.

    Do note that the up voted answer is not accurate. Monochrome bitmaps still have a stride that's a multiple of 4, there is no special rule that makes it 2. A bit of .NET code to demonstrate this:

    var bmp = new Bitmap(1, 1, System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
    var bdata = bmp.LockBits(new Rectangle(0, 0, 1, 1), System.Drawing.Imaging.ImageLockMode.ReadWrite, bmp.PixelFormat);
    Console.WriteLine(bdata.Stride);
    

    Output: 4