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

前端 未结 7 1648
逝去的感伤
逝去的感伤 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:10

    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");
    }
    

提交回复
热议问题