2011-04-12 46 views
39

將圖像輸出到輸出流時,是否需要臨時存儲?將圖像保存到文件時,出現通常與文件夾權限錯誤相關的「通用GDI +」錯誤。C# - 輸出圖像到響應輸出流給GDI +錯誤

我對圖像做的唯一事情就是添加一些文本。即使在不修改的情況下直接輸出圖像,仍然會出現錯誤。例如,這樣做會給我的錯誤:

using (Bitmap image = new Bitmap(context.Server.MapPath("images/stars_5.png"))) 
{ 
    image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png); 
} 

一切工作正常我的本地機器運行Windows 7與IIS 7.5和ASP.NET 2.0。問題發生在使用IIS 6和ASP.NET 2.0運行Windows Server 2003的QA服務器上。

這竟然放棄錯誤的代碼行是:

image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png); 

這裏的堆棧跟蹤:

[ExternalException (0x80004005): A generic error occurred in GDI+.] 
    System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) +378002 
    System.Drawing.Image.Save(Stream stream, ImageFormat format) +36 
    GetRating.ProcessRequest(HttpContext context) in d:\inetpub\wwwroot\SymInfoQA\Apps\tools\Rating\GetRating.ashx:54 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75 
+0

您是否使用任何源代碼管理,每個機會? – 2011-04-12 01:17:30

回答

86

的PNG(等格式)需要被保存到可搜索的數據流。使用中間MemoryStream將這樣的伎倆:

using (Bitmap image = new Bitmap(context.Server.MapPath("images/stars_5.png"))) 
{ 
    using(MemoryStream ms = new MemoryStream()) 
    { 
     image.Save(ms, System.Drawing.Imaging.ImageFormat.Png); 
     ms.WriteTo(context.Response.OutputStream); 
    } 
} 
+4

甜,這工作!謝謝Mark!你偉大的知識拯救了我的一天! – Daniel 2011-04-12 01:31:08

+0

什麼是上述代碼中的上下文任何人都可以告訴我 – Ammar 2016-06-28 07:21:02

+0

這是我見過的ms.writeto的第一個答案,像這樣的所有其他解決方案只是嘗試httpResponseMessage response.Content = new StreamContent(ms.toarray()),它沒有工作爲了我。 幹得好! – 2016-08-02 22:40:04

9

我只是想補充:

Response.ContentType = "image/png"; 

所以它可以直接當它是不是一個img標籤中查看在瀏覽器中。