asp.net绘制png图的一般性错误

Response.Clear();

Response.ContentType = "image/PNG";

img.Save(Response.OutputStream, ChartFormat.Png);

竟然出现异常,是GDI+一般性错误。但是如果格式是Response.ContentType = "image/jpeg";

就不会报错。

好在以前遇到过,改成

Response.ContentType = "image/PNG";

using (MemoryStream ms = new MemoryStream())

{

img.Save(ms, ChartFormat.Png);

Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);

}

就可以输入png图片了。

这是由于Response.OutputStream这个流的无法往回读取造成的,也就是它的CanSeek属性

是false。png图像生成的时候不像jpeg,不是流式的,已经写入的就不再管了,而是需要往回

不断地写入结构数据。但是response流无法往回seek,所以直接用就不行了。改成一个可以

seek的MemoryStream,先生成好png图片,然后再输出到response流。