How to get the bitmap/image from a Graphics object in C#?

前端 未结 7 1607
逝去的感伤
逝去的感伤 2021-02-20 07:34

I want to know what the intermediate state of the buffer where the Graphics object is drawing some stuff. How do I get hold of the bitmap or the image that it is drawing on?

7条回答
  •  遥遥无期
    2021-02-20 08:04

    Since nobody answered the actual question after 9 years...

    // System.Windows.Forms.Internal.IntUnsafeNativeMethods
    [DllImport("gdi32.dll", CharSet = CharSet.Auto, EntryPoint = "GetCurrentObject", ExactSpelling = true, SetLastError = true)]
    public static extern IntPtr IntGetCurrentObject(HandleRef hDC, int uObjectType);
    
    
    IntPtr hdc = graphics.GetHdc();
    // This is a HBITMAP, which is the actual buffer that is being drawn to by hdc.
    IntPtr hbitmap = IntGetCurrentObject(new HandleRef(null, hdc), 7 /*OBJ_BITMAP*/);
    // You can create a Gdiplus::Bitmap object from this, but it will copy all image data.
    // I have not found any way to get a Gdiplus::Bitmap object from a HBITMAP *without* copying it.
    //Bitmap bitmap = Image.FromHbitmap(hbitmap);
    
    // Put these in finally:
    //bitmap.Dispose();
    // NOTE: You cannot use the graphics object before ReleaseHdc is called.
    graphics.ReleaseHdc(hdc);
    

提交回复
热议问题