使用保存到内存流的图像导出文件

时间:2014-04-06 16:00:21

标签: c# asp.net image charts memorystream

我想将图像保存到存储在内存流中的文件中。

我已将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();

3 个答案:

答案 0 :(得分:4)

将响应写入更改为:

response.BinaryWrite(stream1.ToArray());

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

答案 2 :(得分: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;



    }