使用保存到内存流的图像导出文件
本文关键字:图像 导出文件 内存 保存 | 更新日期: 2023-09-27 17:57:11
我想将图像保存到已存储在内存流中的文件中。
我已将 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();
将响应写入更改为:
response.BinaryWrite(stream1.ToArray());
我以前用过这样的东西:
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();
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;
}