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


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

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

更简单的做法

img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
Response.ContentType = "image/gif";
Response.AddHeader("Content-Disposition", "inline;filename=1.gif");

直接保存在 Response.OutputStream 中。最后一句 AddHeader 的目的是让用户在图片上右键另存为的时候,在保存文件对话框中指定默认的文件名。

http://www.cftea.com/c/2008/04/UNNV8Z99H60AVT6U.asp


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM