我们有一种方法可将图像保存为更正格式,如下所示:
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的RAM是免费的。
有什么问题?
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
,现在没问题,是否可以更改应用程序池标识或是安全漏洞?
答案 0 :(得分:2)
图片似乎已损坏,或者文件扩展名可能不正确。
如果扩展名为jpeg
,.NET将尝试将其解码为JPEG。请注意,此行为与浏览器不同:浏览器倾向于查看文件的内容并根据其确定其格式;因此,您可能会误以为jpeg
文件很好,因为它显示在浏览器中,而实际上它包含PNG图像。
如果您在Firefox中打开图像文件,窗口标题栏会告诉您真实文件格式与其文件扩展名无关。
答案 1 :(得分:1)
您必须授予您尝试通过Web应用程序访问的文件夹的权限。如果您使用的是cPanel check here。
答案 2 :(得分:0)
当天晚些时候,我找不到可靠的解决方法。有时环境问题会影响运作。在我的情况下,如果发生异常,我会多次重试该操作。如果你采取这种方法,你的行动应该成功,但要确保行动是幂等的。
e.g。在C#
Action action = () => { //call SaveImageAsCorrectFormat }
try {
action();
}
catch
{
try {
action();
catch (Exception exception) {
//handle
}
}