c# - 保存图像时如何修复此 GDI+ 通用异常?

标签 c# exception bitmap gdi+

如何解决这个 GDI 通用异常?

这是一个异常(exception):

System.Runtime.InteropServices.ExternalException was unhandled
HResult=-2147467259
Message=A generic error occurred in GDI+.
Source=System.Drawing
ErrorCode=-2147467259

代码:

public Bitmap resize(string FileName)
{
  string[] settings;
  string inputFolder = "";
  string qrFolder = "";
  string generalFolder = "";
  string archiveFolder = "";
  string resizedArchiveFolder ="";
  string line;
  int index = 0;
  settings = System.IO.File.ReadAllLines("config.txt");

  foreach (string setting in settings)
  {//access to config file info
    var arr = setting.Split('=');
    if (index == 0)
      inputFolder = arr[1];
    else if (index == 1)
      qrFolder = arr[1];
    else if (index == 2)
      generalFolder = arr[1];
    else if (index == 3)
      resizedArchiveFolder = arr[1];
    else
      archiveFolder = arr[1];

    index++;
  }

  string targetPath = resizedArchiveFolder;
  if (!System.IO.Directory.Exists(targetPath))
  {
    System.IO.Directory.CreateDirectory(targetPath);
  }

  Bitmap a2 = (Bitmap)Image.FromFile(FileName);

  //load file
  a2 = new Bitmap(a2, new Size(a2.Width * 3 / 2, a2.Height * 3 / 2));
  a2.SetResolution(1920, 1080);
  a2.Save(resizedArchiveFolder + System.IO.Path.GetFileName(FileName)); 

  // it throws here when I save
  return a2;
}

最佳答案

加载位图会锁定文件。尝试将另一个图像保存到同一文件将失败并出现此异常。您需要正确执行此操作,处理位图是一项硬性要求:

  Bitmap newa2 = null;
  using (var a2 = (Bitmap)Image.FromFile(FileName)) {
      newa2 = new Bitmap(a2, new Size(a2.Width * 3 / 2, a2.Height * 3 / 2));
      newa2.SetResolution(1920, 1080);
  }
  newa2.Save(Path.Combine(resizedArchiveFolder, Path.GetFileName(FileName))); 
  return newa2;

using 语句确保位图被释放并且文件将不再被锁定。顺便说一句,SetResolution() 参数是无意义的。

如果您仍然遇到问题,那么您的程序中的某处还有另一行(不可见的)代码,它使用resizedArchiveFolder中的位图。它很可能存在于另一个程序中,例如图像查看器。

关于c# - 保存图像时如何修复此 GDI+ 通用异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20010789/

相关文章:

android - 如何将 LinearLayout 转换为图像?

c# - .NET : Calling GetInterface method of Assembly obj with a generic interface argument

c# - 使用 ServiceStack 的 JsonSerializer 序列化包含一些空项的数组

c# - 检查私有(private)字段与捕获异常

android - 多个对话框,第二个不显示

c - 从 Allegro 加载位图后神秘崩溃

c# - 等待后的代码在异步函数(网络表单)中无法按预期工作

c# - 无法弄清楚如何使用关键字 "this"调用属性访问器

c++ - 程序的输出是什么——异常处理?

c++ - 如何将 gdi+ 类位图结构转换为 HDC?