您的位置:首页 > 编程语言 > ASP

ASP.NET实现验证码功能

2011-10-12 16:47 363 查看
注:本文摘自周公的《ASP.NET夜话》一书,P331-P332

后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

public partial class day17_CheckImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//验证码中可能会出现的字符集合
string checkCodeString="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int length = checkCodeString.Length;//验证码字符集合的长度
//设置以宋体来绘制验证字符,并且设置绘制形式为粗体
Font font = new Font("宋体", 24,FontStyle.Bold);
Brush brush = null;//绘制验证码的Brush对象
Color brushColor =new Color();//绘制验证码文字的颜色
string checkCode = string.Empty;//整个显示给用户的验证码字符串
string code = string.Empty;//当前要绘制的验证码字符
//要生成的
Bitmap image = new Bitmap(80, 40);
Graphics g = Graphics.FromImage(image);
g.Clear(Color.White);
//生成随机数的类
Random random = new Random();
for (int i = 0; i < 4; i++)
{
//DateTime.Now.Millisecond表示服务器当前时间的毫秒部分
//采用模运算之后保证current不会超过验证码字符集合的长度
int current = random.Next(DateTime.Now.Millisecond) % length;
//从验证码字符集合中随机截取一个字符来绘制
code = checkCodeString.Substring(current, 1);
checkCode = checkCode + code;
//随机生成绘制验证码字符的颜色
brushColor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255));
brush = new SolidBrush(brushColor);
//绘制刚刚得到的字符串
g.DrawString(code, font, brush, i * 15 + 2, 2);
}
Response.Clear();
Response.ContentType = "image/pjpeg";
//将图象保存到Response的输出流中
image.Save(Response.OutputStream, ImageFormat.Jpeg);
//在Session中保存验证码字符串,以便与用户填写的比较
Session["CheckCode"] = checkCode;
image.Dispose();
Response.End();

}
}


效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: