mihai
mihai

Reputation: 2824

How to Save the drawing (contents) from a panel into any format on a physical storage with C#? (WinForms)

Can someone tell me what i don't make as it should, why i cannot save the drawing to a physical storage?

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        Pen p = new Pen(Color.Red, 3);
        Bitmap bmp = new Bitmap(700, 900);
        Graphics gr = this.CreateGraphics();

        gr.DrawLine(p, new Point(30, 30), new Point(80, 120));
        gr.DrawEllipse(p, 30, 30, 80, 120);

       //when i do this way it saves only a black rectangle, without other drawn content
       bmp.Save(@"C:\testBMP.jpeg", ImageFormat.Jpeg);


       // If i use the following 2 commented lines it saves only a empty rectangle.

       //Rectangle rec = new Rectangle(0, 0, 700, 900);
       // panel1.DrawToBitmap(bmp, rec);


    }

Thank you for advice!

Upvotes: 1

Views: 3673

Answers (3)

vgru
vgru

Reputation: 51292

You have two problems here.

  1. Drawing your panel's contents. This should be done inside its Paint event handler, like this:

    private void panel1_Paint(object sender, PaintEventArgs e)
    {
        using (Pen p = new Pen(Color.Red, 3))
        {
            // get the panel's Graphics instance
            Graphics gr = e.Graphics;
    
            // draw to panel
            gr.DrawLine(p, new Point(30, 30), new Point(80, 120));
            gr.DrawEllipse(p, 30, 30, 80, 120);
        }
    }
    
  2. Saving your panel's contents as an image. This part should be done somewhere else (for example, when you click on a "Save" button):

    private void saveButton_Click(object sender, EventArgs e)
    {
         int width = panel1.Size.Width;
         int height = panel1.Size.Height;
    
         using (Bitmap bmp = new Bitmap(width, height))
         {
             panel1.DrawToBitmap(bmp, new Rectangle(0, 0, width, height));
             bmp.Save(@"C:\testBMP.jpeg", ImageFormat.Jpeg);
         }
    }
    

Upvotes: 3

pstrjds
pstrjds

Reputation: 17448

You need to get a Graphics object from the Image, not from your form. I have not tested this, but it should work.

private void panel1_Paint(object sender, PaintEventArgs e)
{
    using (Pen p = new Pen(Color.Red, 3))
    using (Bitmap bmp = new Bitmap(700, 900))
    using (Graphics gr = Graphics.FromImage(bmp))
    {
       gr.DrawLine(p, new Point(30, 30), new Point(80, 120));
       gr.DrawEllipse(p, 30, 30, 80, 120);

       bmp.Save(@"C:\testBMP.jpeg", ImageFormat.Jpeg);
    }
}

Upvotes: 1

RQDQ
RQDQ

Reputation: 15579

The instance gr has nothing to do with your bitmap (bmp). So you're creating graphics that are associated with the form or control, and have a separate bitmap. When you save the bitmap, you haven't drawn anything in it.

Upvotes: 3

Related Questions