Search code examples
c#lockbits

Why does BitmapData.Stride ignore the size of the rectangle passed to LockBits?


I have an image and want to read the pixel values in a particular region.

I assumed that the rectangle which is the 1st argument of the LockBits() method was there to allow for sub-sections to be specified. When debugging though, I noticed that the value of BitmapData.Stride was 3 x the width of the original bitmap, not 3 x the width of the rectangle.

Why is this? Have I misunderstood the purpose of the rectangle parameter?


Solution

  • It gives GDI+ a way to optimize the mapping of the pixel data to memory. Using a smaller rectangle requires fewer memory pages. The stride is the same, the stride of the original bitmap. And you have to use that value when indexing the scan lines in the bitmap, regardless of the size of the rectangle.