gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:53:24 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com