-1

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

Green Falcon
  • 818
  • 3
  • 17
  • 48
  • 1
    Don't create `Graphics` objects in arbitrary functions. Use the object passed in the `Paint` event and draw only in an event handler of this event. This will also solve the save-to-file problem. And please include the code as text, not as an image. – Nico Schertler Oct 25 '16 at 18:07

1 Answers1

1

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);
    }
}
JuanR
  • 7,405
  • 1
  • 19
  • 30