Saving System.Graphics to bitmap not working

465 views Asked by At

I've created program for drawing. It uses System.graphics to draw rectangles etc. on panel1 in form. Graphics Mouse draw event: Draw I want to get art from panel1 as a bitmap, tried this code:

using (var bmp = new Bitmap(panel1.Width, panel1.Height))
{
    panel1.DrawToBitmap(bmp, new Rectangle(0, 0, bmp.Width, bmp.Height));
    bmp.Save("output.png", System.Drawing.Imaging.ImageFormat.Jpeg);
}

but it generates background color of panel1 in image

1

There are 1 answers

0
JuanR On

Add a handler to the Paint event of the panel somewhere (e.g. form constructor):

panel1.Paint += panel1_Paint;

[Re]draw any graphics in the event:

void panel1_Paint(object sender, PaintEventArgs e)
{            
    DrawLine(e.Graphics);
}

When saving, your code should work just fine:

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\\output.png", System.Drawing.Imaging.ImageFormat.Jpeg);
    }
}