"发生在GDI +&QUOT一般性错误;试图使用Image.Save时错误、发生在、GDI、QUOT

2023-09-02 02:03:18 作者:シ他是王無可替代!

我开发一个Outlook 2010的插件,和我从一个序列化的XML文件加载图像。图像加载罚款,并且我能够将其分配到一个图片对象的WinForm的没有问题。在对象保存在

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);
}

和我得到GDI +中发生一般性错误。我检查该文件夹的写权限,并且它也有写权限。我不能确定什么是错在这里。我也改变了以的imageformat BMP和PNG等,看它是否是一个转换的问题...但事实并非如此。有人会提出一些尝试?

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?

推荐答案

感谢您西门白石在评论回答这个问题。他说:3)确保文件不在使用的任何其他(包括你的code)。

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)."

所以,问题是,我自己的code的使用item.Image对象,并且是preventing GDI +调用Dispose()方法就可以了。解决的办法是在对象复制到一个新的对象,然后使用该对象来写入。由此产生的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);
}