ASP.NET动态绘制汉字、字母和数字验证码

本例利用GDI+技术(图形设备接口:Graphics Device Interface)动态绘制汉字、字母和数字验证码。在利用GDI+绘制图形时需调用Graphics对象来绘制各种图形。

一、技术要点分析

这里利用System.Drawing命名空间中的Graphics对象的DrawString方法和Random对象来绘制4个随机汉字、字母和数字。

1、DrawString方法:在指定位置用指定的System.Drawing.Brush和System.Drawing.Font对象绘制指定的文本字符串

语法:public void DrawString(string s, System.Drawing.Font font, System.Drawing.Brush brush, float x, float y);

各参数意义如下:

s:要绘制的字符串

font:System.Drawing.Font,定义字符串的文本格式

brush: System.Drawing.Brush,确定所绘制文本的颜色和纹理

x,y:所绘制文本左上角坐标

2、Random对象:该对象表示伪随机数生成器,一种能够产生满足某些随机性统计要求的数字序列的设备,该对象常用方法意义如下:

Next():返回非负随机数

Next(int maxValue):返回一个小于所指定最大值的非负随机数

Next(int minValue,int maxValue):返回一个指定范围内的随机数

NextByte(byte[] buffer):用随机数填充指定字节数组的元素

NextDouble():返回一个介于0.0和1.0之间的随机数

Sample():与NextDouble()相同,返回一个≥0.0并且≤1.0的双精度浮点数

二、实现过程

1、绘制表格(4行1列)

2、输入说明性文字

3、添加button控件分别用来点击显示汉字、字母和数字验证码

4、添加image控件,Visible属性设置为False

5、添加Web窗体Hanzi.aspx,Zimu.aspx,Shuzi.aspx并添加4个页面的加载代码(using System.Drawing;)

6、添加4个button控件的单击事件代码

三、======================华丽分割线,各函数代码如下======================

using System.Drawing;//导入命名空间,从而调用Graphics对象绘制图形

using System.Text;      //调用Encoding对象(汉字验证码时用)

/**************************汉字验证码代码**************************/

private object[] CreateString(int strlength)
    {
        /*自定义CreateString方法,用来存储产生的随机汉字区位码*/
        //定义一个数组存储汉字编码的组成元素
        string[] str=new string[16]{“0″,”1″,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″,”a”,”b”,”c”,”d”,”e”,”f”};
        Random ran = new Random();//定义一个随机数对象
        object[] bytes = new object[strlength];
        for (int i = 0; i < strlength; i++)
        {
            //获取第一位区位码
            int ran1 = ran.Next(11, 14);
            string str1 = str[ran1].Trim();

            //获取区位码第二位,并防止数据重复
            ran = new Random(ran1 * unchecked((int)DateTime.Now.Ticks) + i);
            int ran2;
            if (ran1 == 13)
                ran2 = ran.Next(0, 7);
            else
                ran2 = ran.Next(0, 16);
            string str2 = str[ran2].Trim();

            //获取第三位区位码
            ran = new Random(ran2 * unchecked((int)DateTime.Now.Ticks) + i);
            int ran3 = ran.Next(10, 16);
            string str3 = str[ran3].Trim();

            //获取第四位区位码
            ran = new Random(ran3 * unchecked((int)DateTime.Now.Ticks) + i);
            int ran4;
            if (ran3 == 10)
                ran4 = ran.Next(1, 16);
            else if (ran3 == 15)
                ran4 = ran.Next(0, 15);
            else
                ran4 = ran.Next(0, 16);
            string str4 = str[ran4].Trim();

            //定义字节变量存储产生的随机汉字区位码
            byte byte1 = Convert.ToByte(str1 + str2, 16);
            byte byte2 = Convert.ToByte(str3 + str4, 16);
            byte[] stradd = new byte[] { byte1,byte2};
            bytes.SetValue(stradd, i);//将产生的汉字字节放入数组
        }
        return bytes;
    }

    private string GetString(int length)
    {
        /*自定义GetString函数,用来将CreateString方法产生的汉字区位码解码为中文汉字*/
        Encoding gb = Encoding.GetEncoding(“gb2312″);
        object[] bytes = CreateString(length);

        //根据汉字字节解码出中文汉字
        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[])));
        string str = str1 + str2 + str3 + str4;
        Response.Cookies.Add(new HttpCookie(“CheckCode”,str));
        return str;
    }

    private void GraphicsImage(int length)
    {
        //自定义GraphicsImage函数,用来将GetString函数产生对中文汉字绘制成图像显示
        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((GetString(length).Length*22.5)),22);
        Graphics g = Graphics.FromImage(image);//创建画布
        try
        {
            Random random = new Random();//生成随机生成器
            g.Clear(Color.White);//清空图片背景色
            for (int i = 0; i < 1; i++)
            {
                //画图片的背景噪音线
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
            }
            Font font = new System.Drawing.Font(“Couriew New”, 13, System.Drawing.FontStyle.Bold);
            System.Drawing.Drawing2D.LinearGradientBrush brush = new
                System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(GetString(length), font, brush, 2, 2);
            for (int i = 0; i < 50; i++)
            {
                //画图片的前景噪音点
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width – 1, image.Height – 1);//画图片的边框线
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = “image/Gif”;
            Response.BinaryWrite(ms.ToArray());
        }
        catch(Exception ms)
        {
            Response.Write(ms.Message);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        GraphicsImage(4);//调用函数生成4位汉字验证码
    }

/**************************字母验证码代码**************************/

private string GenerateCheckCode()
    {
        //自定义GenerateCheckCode函数,实现生成4个随机字符串
        int number;
        char code;
        string checkCode = string.Empty;
        Random random = new Random();
        for (int i = 0; i < 4; i++)
        {
            number = random.Next();
            code=(char)(‘A’+(char)(number%26));
            checkCode += code.ToString();
        }
        Response.Cookies.Add(new HttpCookie(“CheckCode”,checkCode));
        return checkCode;
    }

    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == String.Empty)
            return;
        System.Drawing.Bitmap image= new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*12.5)),22);
        Graphics g=Graphics.FromImage(image);
        try
        {
            Random random = new Random();//生成随机生成器
            g.Clear(Color.White);//清空图片背景色
            for(int i=0;i<2;i++)
            {
                //画图片的背景噪音线
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
            }
            Font font = new System.Drawing.Font(“Arial”, 13, System.Drawing.FontStyle.Bold);
            System.Drawing.Drawing2D.LinearGradientBrush brush = new
                System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);
            for (int i = 0; i < 100; i++)
            {
                //画图片的前景噪音点
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width – 1, image.Height – 1);//画图片的边框线
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = “image/Gif”;
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        CreateCheckCodeImage(GenerateCheckCode());
    }

/**************************数字验证码代码**************************/

private string NumCode()
    {
        //自定义NumCode函数,实现生成4个随机数字
        int number;
        char code;
        string checkCode = String.Empty;
        Random random =new Random();
        for (int i = 0; i < 4; i++)
        {
            number = random.Next();
            code=(char)(’0′+(char)(number%10));
            checkCode += code.ToString();
        }
        Response.Cookies.Add(new HttpCookie(“CheckCode”, checkCode));
        return checkCode;
    }

    private void NumCodeImage(string checkCode)
    {
        //自定义NumCodeImage函数将NumCode函数产生的4个随机数字制成图片显示出来
        if (checkCode == null || checkCode.Trim() == String.Empty)
            return;
        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
        Graphics g = Graphics.FromImage(image);
        try
        {
            Random random = new Random();//生成随机生成器
            g.Clear(Color.White);//清空图片背景色
            for (int i = 0; i < 2; i++)
            {
                //画图片的背景噪音线
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);
                g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
            }
            Font font = new System.Drawing.Font(“Arial”, 13, System.Drawing.FontStyle.Bold);
            System.Drawing.Drawing2D.LinearGradientBrush brush = new
                System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);
            for (int i = 0; i < 100; i++)
            {
                //画图片的前景噪音点
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);
                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width – 1, image.Height – 1);//画图片的边框线
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = “image/Gif”;
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        NumCodeImage(NumCode());
    }

四、截图


博客来自:http://www.coridc.com/archives/205.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值