How to save Graphics object as image in C#?
Use the Control.DrawToBitmap() method. For example:
private void button1_Click(object sender, EventArgs e) {
using (var bmp = new Bitmap(panel1.Width, panel1.Height)) {
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
bmp.Save(@"c:\temp\test.png");
}
}
In response to your edit:
If you are drawing on the panel using a Graphics
object returned by the CreateGraphics
method, your graphics are not permanent. Anything that you draw on the object will be erased the next time that the control is redrawn. (For more detailed information on this subject, see: https://web.archive.org/web/20131226033137/http://bobpowell.net/picturebox.aspx and https://web.archive.org/web/20141006045615/http://bobpowell.net/creategraphics.aspx)
When you use the DrawToBitmap
method as suggested by Hans Passant's answer, the panel control is getting redrawn, which is causing your drawings to be lost.
Instead, if you want your drawings to be permanent, you need to handle the Paint
event of the panel control. This event is raised every time that the control needs to be redrawn, and provides an instance of PaintEventArgs
that contains a Graphics
object you can use to draw permanently on the control's surface in the same way that you were using the Graphics
object returned by the CreateGraphics
method.
Once you've corrected your drawing code, you can use Hans's solution.