ASP.NET动态生成图片并下载

来源:互联网 发布:手机app编程软件 编辑:程序博客网 时间:2024/04/29 18:19

1.动态生成文字,采用 string name=context .Request ["name"];获取URL传递的参数,传递格式为“*.ashx?name=yioo”

2.文件下载:如果HttpHandler输出的是html,txt,jpeg等类型的信息,那么浏览器会直接显示,如果希望弹出保存对话框,则需要添加Header,添加context.Response.AddHeader("Content-Disposition","attachment:filename="+filename );

filename为建议保存的文件名称,如果包含中文,则需要增加 HttpUtility.UrlEncode进行URL编码。

代码如下:

<%@ WebHandler Language="C#" Class="动态文字" %>using System;using System.Web;public class 动态文字 : IHttpHandler {        public void ProcessRequest (HttpContext context) {        context.Response.ContentType = "image/JPEG";        //URL传递name参数,格式*.ashx?name=ngy        string name=context .Request ["name"];        //保存的文件名,中文需要用UrlEncode编码        string filename = HttpUtility.UrlEncode("图片.jpg");        //添加附近报文头信息        context.Response.AddHeader("Content-Disposition","attachment:filename="+filename );        String fullpath=HttpContext .Current .Server .MapPath ("22.jpg");        using (System.Drawing.Bitmap bitmaip = new System.Drawing.Bitmap(fullpath))        {            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmaip))            {                g.DrawString(name,new System.Drawing.Font("宋体",30),System .Drawing.Brushes .Red ,182,47);            }            bitmaip.Save(context .Response .OutputStream ,System .Drawing .Imaging .ImageFormat .Jpeg );        }        context.Response.WriteFile("22.jpg");                   }     public bool IsReusable {        get {            return false;        }    }}

3.在浏览器中传递name=yioo,效果如图所示: