数字加字母验证码和汉字验证码

来源:互联网 发布:c 调用caffe模型 编辑:程序博客网 时间:2024/05/16 06:54

//生成验证码(数字加字母或者汉字)


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.Text;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

public partial class SystemPages_ValidateCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //  4位数字的验证码
            //int length = 4;        
            //string str_ValidateCode = GenerateCheckCode(length);  //英文加数字验证码

            string str_ValidateCode = GenerateCheckCode(); //汉字验证码
            //  用于验证的Session
            Session["ValidateCode"] = str_ValidateCode;
            CreateImage(str_ValidateCode);
        }
    }

    //生成字母加数字随机字符串
    private string GenerateCheckCode(int length)
    {
        int number;
        string strCode = string.Empty;
        //随机种子
        Random random = new Random();
        for (int i = 0; i < length; i++) 
        {
            //随机整数
            number = random.Next();
            //字符从0-9,A-Z中产生,对应的ASCII码为48-57,65-90
            number = number % 36;
            if (number < 10)
            {
                number += 48;
            }
            else
            {
                number += 55;
            }
            strCode += ((char)number).ToString();
        }
        //将字符串保存在Cookies
        return strCode;
    }

    //生成汉字随机字符串
    private string GenerateCheckCode()
    {
        int number;
        string checkCode = String.Empty;
        System.Random random = new Random();
        Encoding gb = Encoding.GetEncoding("gb2312");
        //调用函数产生4个随机中文汉字编码 
        object[] bytes = CreateRegionCode(6);
        //根据汉字编码的字节数组解码出中文汉字 
        string str1 = gb.GetString((byte[])Convert.ChangeType(bytes[0], typeof(byte[])));
        string str2 = gb.GetString((byte[])Convert.ChangeType(bytes[1], typeof(byte[])));
        string str3 = gb.GetString((byte[])Convert.ChangeType(bytes[2], typeof(byte[])));
        string str4 = gb.GetString((byte[])Convert.ChangeType(bytes[3], typeof(byte[])));
        //输出的控制台 
        checkCode = str1 + str2 + str3 + str4;
        return checkCode;
    }

    //生成编码
    private static object[] CreateRegionCode(int strlength)
    {
        //定义一个字符串数组储存汉字编码的组成元素
        string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

        Random rnd = new Random();

        //定义一个object数组用来
        object[] bytes = new object[strlength];

        /*每循环一次产生一个含两个元素的十六进制字节数组,并将其放入bject数组中
        每个汉字有四个区位码组成
        区位码第1位和区位码第2位作为字节数组第一个元素
        区位码第3位和区位码第4位作为字节数组第二个元素
        */
        for (int i = 0; i < strlength; i++)
        {
            //区位码第1位
            int r1 = rnd.Next(11, 14);
            string str_r1 = rBase[r1].Trim();

            //区位码第2位
            rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机数发生器的

            //种子避免产生重复值
            int r2;
            if (r1 == 13)
            {
                r2 = rnd.Next(0, 7);
            }
            else
            {
                r2 = rnd.Next(0, 16);
            }
            string str_r2 = rBase[r2].Trim();

            //区位码第3位
            rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
            int r3 = rnd.Next(10, 16);
            string str_r3 = rBase[r3].Trim();

            //区位码第4位
            rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
            int r4;
            if (r3 == 10)
            {
                r4 = rnd.Next(1, 16);
            }
            else if (r3 == 15)
            {
                r4 = rnd.Next(0, 15);
            }
            else
            {
                r4 = rnd.Next(0, 16);
            }
            string str_r4 = rBase[r4].Trim();

            //定义两个字节变量存储产生的随机汉字区位码
            byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
            byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
            //将两个字节变量存储在字节数组中
            byte[] str_r = new byte[] { byte1, byte2 };

            //将产生的一个汉字的字节数组放入object数组中
            bytes.SetValue(str_r, i);
        }
        return bytes;
    }


    //生成随机颜色
    public Color GetRandomColor()
    {
        Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
        System.Threading.Thread.Sleep(RandomNum_First.Next(50));
        Random RandomNum_Sencond = new Random((int)DateTime.Now.Ticks);

        //  为了在白色背景上显示,尽量生成深色        int int_Red = RandomNum_First.Next(256);
        int int_Green = RandomNum_Sencond.Next(256);
        int int_Blue = (int_Red + int_Green > 400) ? 0 : 400 - int_Red - int_Green;
        int_Blue = (int_Blue > 255) ? 255 : int_Blue;

        return Color.FromArgb(int_Red, int_Green, int_Blue);
    }
    //创建图片
    public void CreateImage(string str_ValidateCode)
    {
        int int_ImageWidth = str_ValidateCode.Length * 15;
        Random newRandom = new Random();
        //  图高20px Bitmap 对象是用于处理由像素数据定义的图像的对象。        Bitmap theBitmap = new Bitmap(int_ImageWidth, 20);
        //Graphics.FromImage创建新 Graphics 对象。
        Graphics theGraphics = Graphics.FromImage(theBitmap);
        //  白色背景
        theGraphics.Clear(Color.White);
        //  灰色边框   theGraphics.DrawRectangle画矩形   pen(画笔颜色,画笔宽度)
        //DrawRectangle(画笔,x,y,width,heigth)        theGraphics.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, int_ImageWidth - 1, 19);

        //  10pt的字体        Font theFont = new Font("Arial", 10);

        for (int int_index = 0; int_index < str_ValidateCode.Length; int_index++)
        {
            //Substring(1,j) 从i开始取长度为j的字符            string str_char = str_ValidateCode.Substring(int_index, 1);
            //调用随机返回的颜色方法            Brush newBrush = new SolidBrush(GetRandomColor());
            //point(i,j)  i该点的水平位置,  j该点的垂直位置            Point thePos = new Point(int_index * 14 + 1 + newRandom.Next(3), 1 + newRandom.Next(3));
            theGraphics.DrawString(str_char, theFont, newBrush, thePos);
        }

        //  将生成的图片发回客户端        MemoryStream ms = new MemoryStream();
        theBitmap.Save(ms, ImageFormat.Png);//以指定的格式保存到指定的流中

        Response.ClearContent(); //需要输出图象信息 要修改HTTP头
        Response.ContentType = "image/Png";
        Response.BinaryWrite(ms.ToArray());//将一个二进制字符串写入 HTTP 输出流        theGraphics.Dispose();//释放由此 Graphics 对象使用的所有资源。        theBitmap.Dispose();
        Response.End();
    }
   

}



源码:/Files/88223100/CheckCode.rar