I have seen two ways to use lockbits for manipulating bmp pixels. One uses a managed IntPtr followed by a copy of the bmp bytes to an unmanaged array using Marshal.copy. A good example of this is here:
CodeProject: Work with bitmaps faster in C#
By Vano Maisuradze, 15 Aug 2011
The second approach does not require the Marshal.copy. This approach does a cast of the bmp byte pointer directly to an unmanaged byte pointer.
Bitmap^ bmp = gcnew Bitmap(width, height);
BitMapData^ bmpData = bmp->Lockbits( ....)
Byte* pixelArray = (Byte*) (void*) BMPData->Scan0;
pixelArray[...]
a good example of this (written in C#) is here:
"http://bobpowell.net/lockingbits.aspx"
For maximum speed and lower memory use, the second direct cast approach would seem better. There is no copy of the managed bytes into unmanaged memory -- also the manipulated pixels must also be copied back to the managed bytes. For large images this seems burdensome.
However, I have found a problem with the cast approach. I cant seem to effectively prevent a memory leak when working with sequences of images. When I call the lockbits repeatededly on new images I get the leak.
When you try to use
bmp->Dispose()
--- the compiler throws an error. If I use new to allocate the unmanaged
Byte* pixelArray
, followed by a
delete pixdlArray
, I get a run-time error.
Oddly, the memory leak goes away if you use the old-style "delete bmp" after you finish using it.
anyone experienced this ???