Search code examples
c#imagebmpsavefiledialog

Issue while saving image using savefiledialog


I'm using savefiledialog to save an image. Canvas is picturebox and the loaded image is bitmap. When I try to save it the file is created but somehow corrupted. Cause when I try againt load the image or show in different viewer it doesn't work - I mean the saved file is corrupted. There is an method for saving image.

 private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

           System.IO.FileStream fs =
                (System.IO.FileStream)saveFileDialog1.OpenFile();

           try
           {
               switch (saveFileDialog1.FilterIndex)
               {
                   case 1:
                       canvas.Image.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Bmp);
                       break;
                   case 2:
                       canvas.Image.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                       break;
                   case 3:
                       canvas.Image.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Png);
                       break;
                   case 4:
                       canvas.Image.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Tiff);
                       break;
               }

           }
           catch (Exception ex) 
           {
               System.Console.WriteLine("Exception " + ex);
           }

I should also mention the property Filter. saveFileDialog1.Filter has value:

bmp (*.bmp)|*.bmp|jpeg (*.jpeg)|*.jpeg|png (*.png)|*.png|tiff (*.tiff)|*.tiff

Solution

  • I was gonna ask why you have the line

    System.IO.FileStream fs =
        (System.IO.FileStream)saveFileDialog1.OpenFile();
    

    But as it turns out, that's exactly the line causing your problems. You are opening the file to a FileStream. While it's open, you use canvas.Image.Save to write the image to that same file.

    It throws an exception, but since you just write the exception to the console you don't see it.

    Just remove the line I mentioned and your code will work.