Bitmap.Save上的ASP.NET错误“异常(0x80004005):GDI +中发生了一般错误。”

时间:2010-03-12 08:14:27

标签: c# asp.net bitmap drawing gdi+

我有一个函数,它首先从磁盘读取图像,调整大小然后保存到另一个目录。

当我使用Bitmap.Save(目录+ 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 个答案:

答案 0 :(得分:12)

来自ASP Net - GDI+ and SAVE JPG or BMP on the server

  

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

您是否检查了权限?

答案 1 :(得分: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);
    }
  }      
}