ASP.NET在Bitmap.Save时出现错误 "异常 (0x80004005):GDI+ 中发生通用错误。"

6
我有一个函数,首先从磁盘读取图像,调整大小然后保存到另一个目录。
当我使用Bitmap.Save(directory + theimagename)时,它返回了我在问题标题中所述的错误。
我检查了目录是否正确,并且给定的图像名称不存在于该目录中。
奇怪的是,相同的代码在本地计算机上运行良好。但是当我将其上传到我的共享托管空间时,它就无法正常工作。
以下是代码。
bmpOut = new Bitmap(Size, Size);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, Size, Size);
int topBottomPadding = 0; int leftRightPadding = 0;
if (Size > lnNewWidth + 1)
    leftRightPadding = Convert.ToInt32((Size - lnNewWidth) / 2);
else if (Size > lnNewHeight + 1)
    topBottomPadding = Convert.ToInt32((Size - lnNewHeight) / 2);
g.DrawImage(loBMP, leftRightPadding, topBottomPadding, lnNewWidth, lnNewHeight);
Bitmap bmp = new Bitmap(bmpOut);
if (bmp != null)
    bmp.Save(ResizedOutput); // C:\Inetpub\vhosts\DomainName\httpdocs\ProductImages\500px\gigabyte_ga_ep45_ds4_profilelarge[1].jpg
bmp.Dispose();
bmpOut.Dispose();
g.Dispose();
loBMP.Dispose();

堆栈跟踪:

[ExternalException (0x80004005): A generic error occurred in GDI+.]
   System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +377630
   System.Drawing.Image.Save(String filename, ImageFormat format) +69
   System.Drawing.Image.Save(String filename) +25
   Utilities.ResizeImage(String fileName, String mode) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\App_Code\Utilities.cs:181
   Link.ToProductImage(String fileName) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\App_Code\Link.cs:79
   Product.PopulateControls(ProductDetails pd) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\Product.aspx.cs:37
   Product.Page_Load(Object sender, EventArgs e) in c:\inetpub\vhosts\batuhanakcay.com\httpdocs\Product.aspx.cs:20
2个回答

16

来自ASP Net - GDI+和在服务器上保存JPG或BMP

99.9%的情况下,使用GDI时,“发生通用错误”意味着您尝试保存到的目录没有适当的权限。通常,您需要确保允许ASP.NET修改文件的目录。

您检查了权限吗?


我真傻,我一直在搜寻我的代码两天试图找出是什么地方出了问题。你说得对,这应该是我检查的第一件事。我只需要给用户“Plesk IIS WP User(IWAM_plesk(default))”完全权限,然后它就可以工作了。谢谢。 - Batu
1
SO的意思是它可以成为你的第二双眼睛 X-) - Adriaan Stander
我该如何检查这个? - Piero Alberto
我已经通过释放使用GDI+生成的Picturebox控件中的图像来修复了错误。 - Stefan Đorđević

2

当您尝试在网络共享上保存时,也会出现此错误。唯一的解决方法是将位图移到内存流中,并使用文件流将其保存到网络共享中。

以下是一个扩展方法,可以轻松解决此问题:

public static void SaveOnNetworkShare(this System.Drawing.Image aImage, string aFilename, 
  System.Drawing.Imaging.ImageFormat aImageFormat)
{
  using (System.IO.MemoryStream lMemoryStream = new System.IO.MemoryStream())
  {
    aImage.Save(lMemoryStream, aImageFormat);

    using (System.IO.FileStream lFileStream = new System.IO.FileStream(aFilename, System.IO.FileMode.Create))
    {
      lMemoryStream.Position = 0;

      lMemoryStream.CopyTo(lFileStream);
    }
  }      
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接