Issue while saving image using savefiledialog

我怕爱的太早我们不能终老 提交于 2019-12-04 04:58:09

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/11053398/issue-while-saving-image-using-savefiledialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!