1

I'm using a BitmapData object aquired using Bitmap.LockBits to read and write pixel data quickly. The functionality is encapsulated in a class. Can I store refs to the Scan0 and Stride of a BitmapData object or should I read it every time I need to access a pixel? Based on my usage, the same class object can be active for hours, during this period of time would the Scan0/Stride change? Or can I store refs to them in the class to reduce property accesses?

Access every time (a bit slower)

public BitmapData Data;

byte* pixByte = (byte*)BmpData.Scan0 + (Y * BmpData.Stride) + (X * 3); // access pixel of 24bpp image

Storing refs (is this possible?)

public BitmapData Data;
public IntPtr Scan0;
public int Stride;

byte* pixByte = (byte*)Scan0 + (Y * Stride) + (X * 3); // access pixel of 24bpp image
Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607

2 Answers2

2

No, the pixel data for a Bitmap is stored in unmanaged memory. Which is why the type for BitmapData.Scan0 is IntPtr. Unmanaged pointers never change their value, there is no equivalent of a compacting garbage collector for unmanaged heap managers.

However, this is only valid as long as the bitmap is locked. It is generally important that you call Bitmap.UnlockBits() quickly. The bitmap object is not usable while a lock is in effect. Trying to do something like painting the bitmap will fail with an exception while the bitmap is locked. So storing the Scan0 pointer for later use is almost always the wrong thing to do.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Since you're so knowledgeable about everything .NET I'm accepting your answer outright as the conclusive answer. I suppose you would know best. Thanks a lot Hans, for your excellent answers! – Robin Rodricks Mar 08 '13 at 15:40
0

The reference to BitmapData (therefore Scan0) is only valid while you have Bitmap.Lockbits open, once you call UnlockBits the pointer is no longer valid.

You can't effectivly cache that value, however if you know the color depth and size of the bitmap is not going to change you could precompute a lookup table that would remove a lot of the calculations for accessing a pixels position using Stride ( width of a row ) and size of a pixel ( 3 bytes for 24bpp color depth), as those would be basically static.

Brandon Moretz
  • 7,512
  • 3
  • 33
  • 43