(一) 添加一个一般处理程序,
<%@ WebHandler Language="C#" Class="show" %> using System; using System.Web; using System.Drawing;//引用 using System.Web.SessionState;//IRequiresSessionState的命名空间 public class show : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg";//要输出的类型 Bitmap img = new Bitmap(50, 20);//造空白图 Graphics gr = Graphics.FromImage(img);//往哪个图上去绘制 Font font = new Font("宋体", 12, FontStyle.Bold);//设置字体 SolidBrush brush = new SolidBrush(Color.White);//设置刷子 gr.FillRectangle(brush, 0, 0, 50, 20);//刷子绘制的形状 brush.Color = Color.Red;//颜色 string s = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; string str = ""; Random rand = new Random();//初始化随机数 for (int i = 0; i < 4; i++) { int start = rand.Next(62); //生成一个随机的起始位置 str += s.Substring(start, 1).ToString(); } //需要继承接口 context.Session["yanzheng"] = str; gr.DrawString(str, font, brush, 0, 0);//绘制完了图片了 //将图片保存,通过response响应流保存 img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } public bool IsReusable { get { return false; } } }
(二)制作一个主页面 Default
添加一个imagebutton , textbox ,button
不要忘记在imageUrl中添加写的图片的方法。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string txtyanzheng = TextBox1.Text; if (string.IsNullOrWhiteSpace(txtyanzheng)) { } else { string yanzheng = Session["yanzheng"].ToString(); //用Session传值接收过来 if (txtyanzheng == yanzheng) { Response.Write("<script>alert('注册成功')</script>"); } else { Response.Write("<script>alert('验证码不正确')</script>"); } } } }
效果图: