【问题标题】:Export file using image saved to memory stream使用保存到内存流的图像导出文件
【发布时间】:2014-04-06 16:00:20
【问题描述】:

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

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

【问题讨论】:

    标签: c# asp.net image charts memorystream


    【解决方案1】:

    将响应写入更改为:

    response.BinaryWrite(stream1.ToArray());
    

    【讨论】:

      【解决方案2】:

      我以前用过这样的东西:

      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();
      

      【讨论】:

      • 也许试试 Response.BinaryWrite 而不是 Response.Write
      【解决方案3】:
          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;
      
      
      
          }
      

      【讨论】:

      • 使用 Web API 2 和
      猜你喜欢
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多