How to find reason for Generic GDI+ error when saving an image?

前端 未结 10 1570
心在旅途
心在旅途 2020-11-27 19:03

Having a code that works for ages when loading and storing images, I discovered that I have one single image that breaks this code:

const string i1Pa         


        
10条回答
  •  半阙折子戏
    2020-11-27 19:18

    I found this question because I also faced the similar error and the file was actually created with zero length (if you don't see any file, first check the permissions to write into folder as other answers suggest). Although my code was slightly different (I use stream to read the image from memory, not from file), I think my answer may be helpful to anyone facing similar problem.

    It may looks counter-intuitive, but you can't really dispose memory stream until you finish with image.

    NOT WORKING:

    Image patternImage;
    
    using (var ms = new MemoryStream(patternBytes)) {
        patternImage = new Bitmap(ms);
    }
    
    patternImage.Save(patternFile, ImageFormat.Jpeg);
    

    Just don't dispose the stream until you done with image.

    WORKS:

    using (var ms = new MemoryStream(patternBytes)) {
        patternImage = new Bitmap(ms);
        patternImage.Save(patternFile, ImageFormat.Jpeg);
    }
    

    What is misleading:

    • Error message doesn't really tell you anything
    • You can see the image properties, like width and height, but can't save it

提交回复
热议问题