有時候我們生成的圖片並不需要保存到磁盤中,而是直接輸出到頁面,比如驗證碼、實時報表等,如何做呢?請參考如下:
protected void Page_Load(object sender, EventArgs e)
{
System.Drawing.Bitmap img = new System.Drawing.Bitmap(300, 100);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(img);
System.Drawing.Font font = new System.Drawing.Font("宋體", 16); //字體與大小
System.Drawing.Brush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
graphics.DrawString("www.cftea.com", font, brush, 50, 50); //寫字,最后兩個參數表示位置
//將圖片保存到內存流中
System.IO.MemoryStream stream = new System.IO.MemoryStream();
img.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
//在頁面上輸出
Response.Clear();
Response.ContentType = "image/gif";
Response.BinaryWrite(stream.ToArray());
stream.Close();
stream.Dispose();
graphics.Dispose();
img.Dispose();
Response.End();
}
{
System.Drawing.Bitmap img = new System.Drawing.Bitmap(300, 100);
System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(img);
System.Drawing.Font font = new System.Drawing.Font("宋體", 16); //字體與大小
System.Drawing.Brush brush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
graphics.DrawString("www.cftea.com", font, brush, 50, 50); //寫字,最后兩個參數表示位置
//將圖片保存到內存流中
System.IO.MemoryStream stream = new System.IO.MemoryStream();
img.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
//在頁面上輸出
Response.Clear();
Response.ContentType = "image/gif";
Response.BinaryWrite(stream.ToArray());
stream.Close();
stream.Dispose();
graphics.Dispose();
img.Dispose();
Response.End();
}
更簡單的做法
img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
Response.ContentType = "image/gif";
Response.AddHeader("Content-Disposition", "inline;filename=1.gif");
Response.ContentType = "image/gif";
Response.AddHeader("Content-Disposition", "inline;filename=1.gif");
直接保存在 Response.OutputStream 中。最后一句 AddHeader 的目的是讓用戶在圖片上右鍵另存為的時候,在保存文件對話框中指定默認的文件名。