Search code examples
c#pictureboxfile-formatsavefiledialog

How to save a PictureBox image in varying formats?


I have a picture box that will contain an image generated during run-time. I need to save this image using a SaveFileDialog, for which I have found the fallowing code:

 private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
    {
        pictureBox.Image.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
    }

This works however, I need to allow the user to specify in the FileDalog what format they want it to be saved as. The allowed formats for the user:

Bitmap (*.bmp),

GIF (*.gif),

JPEG (*.jpg),

and PNG (*.png). Any examples or recommendations on how to accomplish this would be much appreciated.


Solution

  • Somthing like this could be a good place to start

            var fd = new SaveFileDialog();
            fd.Filter = "Bmp(*.BMP;)|*.BMP;| Jpg(*Jpg)|*.jpg";
            if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                switch (Path.GetExtension(fd.FileName))
                {
                    case ".BMP":
                        pictureBox.Image.Save(fd.FileName, System.Drawing.Imaging.ImageFormat.Bmp);
                        break;
                    case ".Jpg":
                        pictureBox.Image.Save(fd.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                        break;
                    default:
                        break;
                }
            }