X+Y=? 这种验证码的实现
入正题 上代码
一般处理程序来实现验证码
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Web;
using System.Web.SessionState;
public class Handler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/gif";
//建立Bitmap对象,绘图
Bitmap basemap = new Bitmap(200, 60);
Graphics graph = Graphics.FromImage(basemap);
graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
Random r = new Random();
string letters = "1234567890";
string letter;
StringBuilder s = new StringBuilder();
string[] arrays = new string[2];
//添加随机的2个数字
for (int x = 0; x < 2; x++)
arrays[x] = letters.Substring(r.Next(0, letters.Length - 1), 1);
graph.DrawString(arrays[0] + "+" + arrays[1] + "= ?", font, new SolidBrush(Color.Black), 38, r.Next(0, 15));
//混淆背景
Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
for (int x = 0; x < 3; x++)
graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
//将图片保存到输出流中
basemap.Save(context.Response.OutputStream, ImageFormat.Gif);
context.Session["CheckCode"] = Convert.ToInt32(arrays[0]) + Convert.ToInt32(arrays[1]);
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
前台显示代码
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> <img src="Handler.ashx" alt="验证码" style="height: 19px; width: 68px"/> </div> </form> </body> </html>
就这样的 图片是我放大了 所以看着不清晰

浙公网安备 33010602011771号