生成随即验证码图片

主要步骤为:

  • 随机生成字符串,并将字符串保存到Session或者Cookie中
  • 将生成字符串绘 制成图片,并设置<img>元素的src为动态生成的图片  //即生成随机验证码图片的页面

 

生成随机验证码图片代码:

//可放置在生成验证码图片的页面并执行,即<img>元素的src指向的页面

CheckImage.aspx.cs页面     //前台页面没做任何处理

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 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();

    }
}


需显示验证码页面调用只需添加<img>标签即可,如:

  

<img src="CheckImage.aspx" style="cursor:hand" οnclick="this.src='CheckImage.aspx?id=' + Math.random() * 10000" alt="点击刷新验证码" />


 

 onclick事件主要是传入一个不同URL地址,或者是οnclick="this.src='CheckImage.aspx?' + new Date().getMilliseconds();"

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值