Correct way to calculate the stride of a bitmap?

Post your questions regarding programming in C# in here.
1 post Page 1 of 1
Contributors
User avatar
MrAksel
C# Coder
C# Coder
Posts: 1758
Joined: Fri Mar 26, 2010 12:27 pm

I was wondering, what is the correct way to calculate the scanline width of a bitmap? I have this code to calculate its stride (scanline width):
Code: Select all
        public static int GetStride(int Width, PixelFormat format, out int padding)
        {
            int r = (Width * PixelSize(format) / 8);
            padding = r % 4;
            return r + padding;
        }

        public static int PixelSize(PixelFormat PxFormat)
        {
            switch (PxFormat)
            {
                case PixelFormat.Format1bppIndexed:
                    return 1;
                case PixelFormat.Format4bppIndexed:
                    return 4;
                case PixelFormat.Format8bppIndexed:
                    return 8;
                case PixelFormat.Format16bppArgb1555:
                case PixelFormat.Format16bppGrayScale:
                case PixelFormat.Format16bppRgb555:
                case PixelFormat.Format16bppRgb565:
                    return 16;
                case PixelFormat.Format24bppRgb:
                    return 24;
                case PixelFormat.Format32bppArgb:
                case PixelFormat.Format32bppPArgb:
                case PixelFormat.Format32bppRgb:
                    return 32;
                case PixelFormat.Format48bppRgb:
                    return 48;
                case PixelFormat.Format64bppArgb:
                case PixelFormat.Format64bppPArgb:
                    return 64;
            }
            return 0;
        }
But sometimes it fail. I have read that the stride is always a multiple of four, so I make sure the result is padded by the correct amount (r % 4). I have never tested it on other pixel formats than 32 bpp or 24 bpp, as I expect some of the others to fail anyway.

The reason I need this, is because I'm making an image editing library, similar to AForge. I have my own bitmap class (MemoryBitmap), and its constructor has three parameters; Width, Height and Pixel format. These should be enough to calculate size needed in memory.

Whats failing: I have this ToBitmap() function which creates a GDI bitmap, locks its data, copies the MemoryBitmap's data into the GDI bitmap, unlocks the bitmap and returns it. The problem occurs when the stride calculated by my function does not match the stride calculated by GDI. The times it fail, the strides differs with 2.
Is the stride supposed to be a multiple of 2 or 4?
LMAOSHMSFOAIDMT
Laughing my a** of so hard my sombrero fell off and I dropped my taco lmao;


Over 30 projects with source code!
Please give reputation to helpful members!

Image
Image
1 post Page 1 of 1
Return to “General coding help”