user2149431
user2149431

Reputation: 31

Image stride for MSpaint image in C# is +1 byte, why?

I have a problem regarding some pixel-based operations in C#. I wrote a class that serves as an image shell around a Bitmap. It can give you the RGB values of a pixel at a certain (x,y) location in the image much faster than the Bitmap.GetRGB(x,y) color object by using BitmapData and LockBits to get direct access to the image array and read the bytes from there. I added this function to get the RGB in an 0x00RRGGBB mask at a (x,y) pixel.

public unsafe int getPixel(int x, int y)
    {
        byte* imgPointer = (byte*)bmpData.Scan0;
        int pixelPos = 0;
        if (y > 0) pixelPos += (y * bmpData.Stride);
        pixelPos += x * (hasAlpha ? 4 : 3);            

        int blue = *(imgPointer + pixelPos);
        int green = *(imgPointer + pixelPos + 1);
        int red = *(imgPointer + pixelPos + 2);

        int rgb = red << 16;
        rgb += green << 8;
        rgb += blue;

        return rgb;
    }

This works flawlessly for all the images I've worked with thus far, except for any image I generate using MSPaint. For example, I made a 5x1 image in paint containing 5 shades of yellow. When I load this image into my program however, the image stride is 16! I suspected it to be 15 (3 bytes per pixel, 5 pixels) but for some reason after the first three bytes (first pixel) there is an extra byte, and then the rest of the pixels follow in the array.

I have only found this for images that are saved by MSpaint and I was hoping anyone could explain me what that extra byte is for and how to detect that extra byte.

Upvotes: 3

Views: 601

Answers (1)

Joel Rondeau
Joel Rondeau

Reputation: 7586

From MSDN:

The stride is the width of a single row of pixels (a scan line), rounded up to a four-byte boundary. If the stride is positive, the bitmap is top-down. If the stride is negative, the bitmap is bottom-up.

So stride is always a multiple of 4, and for your 3x5, will round up to 16.

Upvotes: 3

Related Questions