验证码怎样实现的例子

using System;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {    
        this.getJpg();
    }
    //将验证码画在图像上
    protected void getJpg()
    {
        //定义一个长度
        int length = 6;
        //创建一个图像
        Bitmap Bit = new Bitmap(120, 40);
        //创建一个绘图图像
        Graphics g = Graphics.FromImage(Bit);
        //调用getLength()方法来获取图像中显示的验证码
        string strcheck = this.getLength(length);
        //为图像添加背景色
        g.Clear(Color.DarkGreen);
        //图像中验证码显示的字体与大小
        Font f = new Font("@Batang",20);
        //文本的布局,此处为空,默认布局
        StringFormat SF = new StringFormat();
        //在指定的区域绘制字符串
        g.DrawString(strcheck, f, Brushes.Orange, 1f, 1f, SF);
        //为背景随机添加横线,为了不让横线重复,取了时间的毫秒部分
        Random R = new Random(DateTime.Now.Millisecond);

        for (int i = 0; i < 10; i++)
        {
            int y = R.Next(Bit.Height);

            g.DrawLine(new Pen(Color.Black,0), 0, y, Bit.Width, y);
        }
        //创建一个存取流,需要倒包using System.IO
        MemoryStream MS = new MemoryStream();
        //将图像以Jpg的格式保存到MS流中
        Bit.Save(MS, System.Drawing.Imaging.ImageFormat.Jpeg);
        //将二进制字符串写入到Http输出流
        this.Response.BinaryWrite(MS.ToArray());
      
    }

    //得到验证码的数字
    private string getLength(int strlength)
    {
        //自定义一个字符串
        string str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        //定义一个空的字符串,以保存验证码数字
        string str1 = "";
        //随机生成数字,取时间毫秒部分是为了不让数字重复
        Random RD = new Random(DateTime.Now.Millisecond);

        for (int i = 0; i < strlength; i++)
        {
            str1 += str[RD.Next(0,61)];//在0-61之间取数                  
        }

        return str1;//返回得到的验证码
    }
}

 

 

最后结果:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值