ASP.NET 画图与图像处理-如何直接输出到页面

作者:vkvi 来源:ITPOW(原创) 日期:2007-8-30

有时候我们生成的图片并不需要保存到磁盘中,而是直接输出到页面,比如验证码、实时报表等,如何做呢?请参考如下:

    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.itpow.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.OutputStream 中。最后一句 AddHeader 的目的是让用户在图片上右键另存为的时候,在保存文件对话框中指定默认的文件名。

相关文章