Search code examples
c#bytebmplockbits

C# - Remove Bitmap padding


I was wondering if there's a way in order to remove the padding generated by the 24 bit Bitmap for each scan line.

What I mean is like this :

Original [Pure Cyan 24 Bit BMP] :

FF FF 00 FF FF 00 FF FF **00 00** FF FF 00 FF FF 00 FF FF 00

Desired output [Removed Padding] :

FF FF 00 FF FF 00 FF FF **00** FF FF 00 FF FF 00 FF FF 00

Here's my code for getting the pixel data.

            Bitmap tmp_bitmap = BitmapFromFile;

            Rectangle rect = new Rectangle(0, 0, tmp_bitmap.Width, tmp_bitmap.Height);
            System.Drawing.Imaging.BitmapData bmpData =
                tmp_bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
                PixelFormat.Format24bppRgb);

            int length = bmpData.Stride * bmpData.Height;

            byte[] bytes = new byte[length];

            // Copy bitmap to byte[]
            Marshal.Copy(bmpData.Scan0, bytes, 0, length);
            tmp_bitmap.UnlockBits(bmpData);

Thank you in advance.


Solution

  • No, you'll have to remove it yourself. Padding is added to ensure that the start of a scanline in the bitmap starts at a multiple of 4. So getting padding is pretty likely when the pixel format is 24bpp, bmp_bitmap.Width * 3 is only divisible by 4 by accident.

    You'll need a loop to copy each line. Something like this:

    byte[] bytes = new byte[bmpData.Width * bmpData.Height * 3];
    for (int y = 0; y < bmpData.Height; ++y) {
        IntPtr mem = (IntPtr)((long)bmpData.Scan0 + y * bmpData.Stride);
        Marshal.Copy(mem, bytes, y * bmpData.Width * 3, bmpData.Width * 3);
    }