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

前端 未结 10 1505
心在旅途
心在旅途 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:36

    Key Information:

    // Using System.Drawing.Imaging:
    new Bitmap(image).Save(memoryStream, ImageFormat.Jpeg);
    

    You MUST Cast the Image to a Bitmap to Save it.

    Using:

    // Using System.Drawing.Imaging:
    image.Save(memoryStream, ImageFormat.Jpeg);
    

    WILL throw the Error:

    Generic GDI+ error when saving an image

    0 讨论(0)
  • 2020-11-27 19:37

    In my case I have accidentally deleted the directory where image was getting stored.

    0 讨论(0)
  • 2020-11-27 19:39

    The reason may be that the image is loaded lazily and the loading process is not yet finished when you try to save it.

    Following what's said in this blog post (assuming you're German by the picture you linked in your question) provides a possible solution. Also this SO question's accepted answer indicates this is due to the fact the image file you're trying to save to is locked.

    EDIT
    For Ulysses Alves, from the linked blog entry: If you load an image using Image.FromFile() it remains locked until it is disposed of. This prevents calls to Save().

    pictureBox1.Image = Image.FromFile("C:\\test\\test1.jpg");
    pictureBox1.Image.Save("C:\\test\\test2.jpg");
    

    The above code throws an error.

    To make it work, you need to copy the image. The following code works:

    pictureBox1.Image = Image.FromFile("C:\\test\\test1.jpg");
    Image copy = pictureBox1.Image;
    copy.Save("C:\\test\\test2.jpg")
    
    0 讨论(0)
  • 2020-11-27 19:39

    Just use the visual studio as administrator or run the application created by the code as administrator it should work smoothly. It is user access rights issue. I faced the same and resolved it by running visual studio as administrator.

    0 讨论(0)
提交回复
热议问题