Click here to Skip to main content
15,901,373 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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[...]     //accesses the pixel color bytes 

a good example of this (written in C#) is here:


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 ???
Updated 3-Aug-13 7:03am
Fredrik Bornander 3-Aug-13 13:02pm    
You are calling UnlockBits when done using the bits locked with LockBits, right?

thanks for the comments ...
I have switched my code to use the Marshall to copy the bits from the bitmap.
in my limited testing so far, I havenet seen a performance penalty as Sergey suggested.
Share this answer
Always use Marshal; direct cast approach is not really correct; it would be like using managed memory without pinning: it could work in some situations, but only by chance. And the solution using Marshal with LockBits doesn't really compromise performance.

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900