如何解决这个 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/