2016-08-22 72 views
-1

我想救我從位圖在我的項目給定路徑創建的圖像,但我得到這個錯誤:Additional information: A generic error occurred in GDI+.保存時ASP.NET MVC錯誤圖像

這是代碼:

 public void SaveCaptchaImage(string name) 
     { 
      Bitmap image = new Bitmap(128, 64); 
      string path = "/content/images"; 

      if (System.IO.File.Exists(path + name)) 
       System.IO.File.Delete(path + name); 

      using (Pen myPen = new Pen(Color.Red, 5)) 
      using (Brush myBrush = new SolidBrush(Color.Silver)) 
      using (Font myFont = new Font("Arial", 16)) 
      using (Graphics graphObject = Graphics.FromImage(image)) 
      { 
       graphObject.FillRectangle(myBrush, new Rectangle(0, 0, 128, 64)); 
       graphObject.DrawString(GetRandomCaptcha(), myFont, myBrush, new Point(20, 20)); 
       image.Save(path + name + ".png", ImageFormat.Png); 
      } 
      image.Dispose(); 
     } 

唯一的例外發生在這一行:

image.Save(path + name + ".png", ImageFormat.Png); 

我能做些什麼來解決這個問題?

編輯:我不明白爲什麼我被downvoted,但確定。

+0

我建議你總是使用'Path.Combine'來結合路徑,而不是隻是連接字符串 - 因爲除非'name'以斜槓開始,否則你會用'image.Save(「pathname.png 「,ImageFormat.Png);'而不是'image.Save(」path/name.png「,ImageFormat.Png);' – stuartd

回答

0

包裹你的路徑與Server.MapPath,如:

image.Save(HttpContext.Current.Server.MapPath(Path.Combine(path, name + ".png")), ImageFormat.Png); 

獲得絕對路徑,而不是相對的。

和使用Path.Combine方法像@stuartd建議在評論中。