How can I overwrite a System.Drawing.Bitmap onto an existing GDI bitmap?

Posted by MusiGenesis on Stack Overflow See other posts from Stack Overflow or by MusiGenesis
Published on 2010-04-14T01:36:18Z Indexed on 2010/04/14 1:43 UTC
Read the original article Hit count: 441

Filed under:
|
|
|

If I have a .Net Bitmap, I can create from it a GDI bitmap by calling the Bitmap's GetHbitmap() method.

Bitmap bmp = new Bitmap(100, 100);
IntPtr gdiBmp = bmp.GetHbitmap();

This works fine, but every time you call GetHbitmap, Windows has to allocate new memory for the object that gdiBmp references.

What I'd like to do - if possible - is write a function (I know PInvoke will be necessary here) that also generates a GDI bitmap copy of a Bitmap, but that uses an existing object instead of allocating a new one. So it would look something like this (if it were an extension method of Bitmap):

//void OverwriteHbitmap(IntPtr gdi)

Bitmap bmp1 = new Bitmap(100, 100);
IntPtr gdi1 = bmp1.GetHbitmap();

Bitmap bmp2 = new Bitmap(100, 100);
bmp2.OverwriteHbitmap(gdi1);

How can I do this? I assume I'll need to know the structure of a GDI bitmap, and probably I can use LockBits and BitmapData for this, but I'm not sure exactly how.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET