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

dattebayo picture dattebayo · Mar 15, 2011 · Viewed 30.6k times · Source

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?

Answer

Cody Gray picture Cody Gray · Mar 15, 2011

I'm not really sure if I understand what you're asking for, as your question is very unclear.

If you want to know how to save the contents of a Graphics object to a bitmap, then the answer is that there's no direct approach for doing so. Drawing on a Graphics object is a one-way operation.

The better option is to create a new Bitmap object, obtain a Graphics object for that bitmap, and draw directly onto it. The following code is an example of how you might do that:

// Create a new bitmap object
using (Bitmap bmp = new Bitmap(200, 300))
{
    // Obtain a Graphics object from that bitmap
    using (Graphics g = Graphics.FromImage(bmp))
    {
        // Draw onto the bitmap here
        // ....
        g.DrawRectangle(Pens.Red, 10, 10, 50, 50);
    }

    // Save the bitmap to a file on disk, or do whatever else with it
    // ...
    bmp.Save("C:\\MyImage.bmp");
}