c#中创建新位图时出现异常
本文关键字:异常 位图 创建 新位图 | 更新日期: 2023-09-27 18:07:05
我们有一个方法可以将图像保存为更正后的格式,如下所示:
public static string SaveImageAsCorrectFormat(string tempFilePath, string newFileName, string destinationDirectoryPath)
{
using (Image image = new Bitmap(tempFilePath))// Exception : Parameter is not valid.
{
string extension = image.RawFormat.GetExtension();
string newAbsoluteFilePath = Path.Combine(destinationDirectoryPath, string.Format("{0}.{1}", newFileName, extension));
image.Save(newAbsoluteFilePath, image.RawFormat);
return newAbsoluteFilePath;
}
}
但是在下一行中出现了异常:
//Parameter is not valid.
using (Image image = new Bitmap(tempFilePath))
我将其更改为以下内容,但Out of memory
已经发生:
// Out of memory
using (Bitmap image = (Bitmap)Image.FromFile(tempFilePath))
图像大小为10KB,空闲内存为10GB。
有什么问题吗?
p。S:
我在本地没有这个问题。但是当我在服务器上发布软件时,出现了这个问题。
我用的是windows Server 2012 R2
和IIS 8.5.9600.16384
。应用程序(网站)完全控制IIS_IUSRS
和IUSR
。
我认为这个问题与权限无关,因为我可以用以下代码打开文件:
using (FileStream fileStream = File.Open(tempFilePath, FileMode.Open)) // OK
using (Image image = new Bitmap(fileStream))// Exception : Parameter is not valid.
解决方案:
我将网站application pool identity
更改为Local System
,现在可以了,是可以更改应用程序池身份还是存在安全漏洞?
似乎图像已损坏,或者可能只是文件扩展名错误。
如果扩展名是jpeg
, . net将尝试将其解码为JPEG。请注意,这种行为与浏览器不同:浏览器倾向于查看文件的内容,并根据该内容决定其格式;因此,您可能会误解jpeg
文件很好,因为它显示在浏览器中,而实际上它包含PNG图像。
如果您在Firefox中打开图像文件,窗口标题栏会告诉您真正的文件格式与文件扩展名无关。
您必须授予您试图通过web应用程序访问的文件夹权限。如果你使用的是cPanel,点击这里
当天晚些时候,但我找不到一个可靠的解决方案。有时环境问题会影响操作。在我的例子中,如果发生异常,我将多次重试该操作。如果你采用这种方法,你的行动应该会成功,但要确保这个行动是幂等的。
。在c#中
Action action = () => { //call SaveImageAsCorrectFormat }
try {
action();
}
catch
{
try {
action();
catch (Exception exception) {
//handle
}
}