KevinA
KevinA

Reputation: 629

Bitmap Scan0, Stride off

I'm writing a program that apply xored delta's to a existing bitmap. The problem i'm having is it seems to be 5 pixles off in the first iteration leading too some interesting color effects

private void ApplyDelta(ref Bitmap bitmapA, Bitmap bitmapB, Rectangle bounds)
    {
        if (bounds.Width != bitmapB.Width || bounds.Height != bitmapB.Height || bitmapA.PixelFormat != bitmapB.PixelFormat)
        {
            return;
        }

        BitmapData bmdA = bitmapA.LockBits(bounds, ImageLockMode.ReadWrite, bitmapA.PixelFormat);
        BitmapData bmdB = bitmapB.LockBits(new Rectangle(0, 0, bitmapB.Width, bitmapB.Height), ImageLockMode.ReadOnly, bitmapB.PixelFormat);
        unsafe
        {
            int bytesPerPixel = Image.GetPixelFormatSize(bitmapA.PixelFormat) / 8;
            for (int y = 0; y < bmdA.Height; y++)
            {
                byte* rowA = (byte*)bmdA.Scan0 + (y * bmdA.Stride);
                byte* rowB = (byte*)bmdB.Scan0 + (y * bmdB.Stride);
                for (int x = 0; x < bmdA.Width * bytesPerPixel; x++)
                {
                    rowA[x] ^= rowB[x];
                }
            }
        }

        bitmapA.UnlockBits(bmdA);
        bitmapB.UnlockBits(bmdB);
    }

Result:

Picture Error

Upvotes: 0

Views: 872

Answers (1)

Chris Dunaway
Chris Dunaway

Reputation: 11216

The Stride is the width of one row of pixels plus some padding so that each row begins on a 4 byte boundary for efficiency. From BobPowell.net:

The Stride property ... holds the width of one row in bytes. The size of a row however may not be an exact multiple of the pixel size because for efficiency, the system ensures that the data is packed into rows that begin on a four byte boundary and are padded out to a multiple of four bytes. This means for example that a 24 bit per pixel image 17 pixels wide would have a stride of 52. The used data in each row would take up 317 = 51 bytes and the padding of 1 byte would expand each row to 52 bytes or 134 bytes. A 4BppIndexed image of 17 pixels wide would have a stride of 12. Nine of the bytes, or more properly eight and a half, would contain data and the row would be padded out with a further 3 bytes to a 4 byte boundary.

See this article for more detailed information.

Edit: Re-reading your question, I'm not sure this is applicable to your situation. But make sure in your calculations that you keep the padding in mind.

Upvotes: 1

Related Questions