Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 491
tguclu Avatar asked Jun 30 '09 12:06

tguclu


1 Answers

Here is my solution with additional support to various file types:

    public void ExportToBmp(string path)
    {
        using(var bitmap = new Bitmap(pictureBox.Width, pictureBox.Height))
        {
        pictureBox.DrawToBitmap(bitmap, pictureBox.ClientRectangle);
        ImageFormat imageFormat = null;

        var extension = Path.GetExtension(path);
        switch (extension)
        {
            case ".bmp":
                imageFormat = ImageFormat.Bmp;
                break;
            case ".png":
                imageFormat = ImageFormat.Png;
                break;
            case ".jpeg":
            case ".jpg":
                imageFormat = ImageFormat.Jpeg;
                break;
            case ".gif":
                imageFormat = ImageFormat.Gif;
                break;
            default:
                throw new NotSupportedException("File extension is not supported");
        }

        bitmap.Save(path, imageFormat);
        }
    }
like image 122
0lukasz0 Avatar answered Oct 15 '22 13:10

0lukasz0