2014-04-06 136 views
1

我想将图像保存到已存储在内存流中的文件。使用保存到内存流的图像导出文件

我已将asp.net图表保存到内存流中。

stream1 = new MemoryStream(); 
chart_location_3.SaveImage(stream1, ChartImageFormat.Png); 

然后我使用下面的代码导出为jpg。它触发保存提示,并创建文件,但图像将无法打开(“这不是一个有效的位图文件,或目前不支持其格式”)

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 

System.Drawing.Image img; 

img = System.Drawing.Image.FromStream(stream1); 
response.ClearContent(); 
response.Clear(); 
Response.ContentType = "image/jpg"; 
response.AddHeader("Content-Disposition", "attachment; filename= Exported.jpg;"); 
response.Write(img); 
response.Flush(); 
response.End(); 

回答

4

变化的响应写:

response.BinaryWrite(stream1.ToArray()); 
0

我用这样的事情之前:

http://www.dotnetperls.com/ashx

它生成图像浏览器在飞行中。希望能帮助到你。


根据dotnetperls的答案,它使用response.binarywrite。如下更改代码:

System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; 

System.Drawing.Image img; 

img = System.Drawing.Image.FromStream(stream1); 
response.ClearContent(); 
response.Clear(); 
Response.ContentType = "image/jpg"; 
response.AddHeader("Content-Disposition", "attachment; filename= Exported.jpg;"); 
response.BinaryWrite(img); 
response.Flush(); 
response.End(); 
+0

不使用的内存,虽然流.. – Chris

+0

也许尝试Response.BinaryWrite代替的Response.Write –

0
public HttpResponseMessage GetStatChart() 
    { 
     HttpResponseMessage response = new HttpResponseMessage(); 

     var chartImage = new Chart(600, 400); 
     chartImage.AddTitle("Chart Title"); 
     chartImage.AddSeries(
       name: "Employee", 
       chartType: "Pie", 
       axisLabel: "Name", 
       xValue: new[] { "Peter", "Andrew", "Julie", "Mary", "Dave" }, 
       yValues: new[] { "2", "6", "4", "5", "3" }); 
     byte[] chartBytes = chartImage.GetBytes(); 

     response.Content = new ByteArrayContent(chartBytes); 
     response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); 

     return response; 



    } 
+0

使用Web API 2和 Scott