Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

c# - "A generic error occurred in GDI+" when attempting to use Image.Save

I am developing an Outlook 2010 Add-In, and am loading an image from a serialized XML file. The image loads fine, and am able to assign it to a pictureBox object on a Winform no problem. The object is saved in

[XmlIgnore]
public Bitmap Image
{
   get { return this.templateImage; }
   set { this.templateImage = value; }
 }

When, I attempt to save the physical file onto the harddisk however, I am doing:

string filePath = Path.Combine(dirPath, item.Id + ".jpg");
try
{
    item.Image.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception e)
{
    Debug.WriteLine("DEBUG::LoadImages()::Error attempting to create image::" + e.Message);
}

and am getting an A generic error occurred in GDI+. I've checked the write permissions on the folder, and it does have write permissions. I'm unsure what is wrong here. I've also changed the ImageFormat to bmp and png and so forth to see if it was a conversion problem... but it isn't. Would anybody suggest something to try?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thank you to Simon Whitehead for answering this in the comments. He said, "3) Make sure the file is not in use by anything else (including your code)."

So the problem was that my own code was using the item.Image object, and was preventing GDI+ to call the dispose() method on it. The solution was to copy the object into a new object, then use that object to "Write." The resulting code is as follows:

try
{
   using (Bitmap tempImage = new Bitmap(item.Image)) 
   {
      tempImage.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
   }    
}
catch (Exception e)
{
    Debug.WriteLine("DEBUG::LoadImages()::Error attempting to create image::" + e.Message);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...