Is it possible to BitBlt directly from a GDI+ bitmap?

巧了我就是萌 提交于 2019-12-03 03:40:54
jnm2

After searching for days, it suddenly hit me that the answer had been staring me in the face all the time! I was creating a GDI+ bitmap from a pointer to a byte array. Then trying to create an HBITMAP using the same pointer. But I could just as easily create the HBITMAP first and use the pointer from that to create the GDI+ bitmap.

It works like a charm! You can mix GDI and GDI+ operations however you like. The image is both plain GDI and GDI+ at once. Instead of using DrawImage, you can BitBlt from the exact same pixel data!

Here's the code:

// Create the HBITMAP
BITMAPINFO binfo = new BITMAPINFO();
binfo.biSize = (uint)Marshal.SizeOf(typeof(BITMAPINFO));
binfo.biWidth = width;
binfo.biHeight = height;
binfo.biBitCount = (ushort)Image.GetPixelFormatSize(pixelFormat);
binfo.biPlanes = 1;
binfo.biCompression = 0;

hDC = CreateCompatibleDC(IntPtr.Zero);

IntPtr pointer;
hBitmap = CreateDIBSection(hDC, ref binfo, 0, out pointer, IntPtr.Zero, 0);

// Create the GDI+ bitmap using the pointer returned from CreateDIBSection
gdiBitmap = new Bitmap(width, height, width * binfo.biBitCount >> 3, pixelFormat, pointer);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!