ASP.NET实现验证码功能

注:本文摘自周公的《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();

    }
}

效果图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值