How to save a picturebox control as a jpeg file after it's edited

tguclu picture tguclu · Jun 30, 2009 · Viewed 74.5k times · Source

I have a PictureBox on my Windows Forms application.

I load a picture in it and I have enabled the Paint event in my code. It draws a rectangle.

Like this:

private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
    Graphics gr = e.Graphics;
    Pen p = new Pen(Color.Red);
    p.Width = 5.0f;
    gr.DrawRectangle(p, 1, 2, 30, 40);
}

And I click the "save" button:

private void button2_Click(object sender, EventArgs e)
{
    pictureBox1.Image.Save(@"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000test.jpg",ImageFormat.Jpeg);
}

But the saved file never contains the rectangle that I drew.

Does anyone have any idea?

Answer

tguclu picture tguclu · Jun 30, 2009

Thanks.Your anwers all helped. This worked

        private void button1_Click(object sender, EventArgs e)
    {
        pictureBox1.ImageLocation=@"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000.jpg" ;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        pictureBox1.Image.Save(@"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000test.jpg",ImageFormat.Jpeg);
    }

    private void pictureBox1_Paint(object sender, PaintEventArgs e)
    {

    }

    private void button3_Click(object sender, EventArgs e)
    {
        Bitmap bmp = new Bitmap(pictureBox1.Image);
        Graphics gr = Graphics.FromImage(bmp);
        Pen p = new Pen(Color.Red);
        p.Width = 5.0f;
        gr.DrawRectangle(p, 1, 2, 30, 40);
        pictureBox1.Image = bmp;
    }