手写一个生成验证码的方法

最近在研究识别验证码,要是想要识别的话,那还是需要先自己来实现一个验证码的功能,废话不多说直接放代码:

 /// <summary>
    /// 生成验证码的函数
    /// </summary>
    private void CreateImage() {
        string chkCode = string.Empty;
        //颜色列表,用户验证码、噪线、噪点
        Color[] color = {Color.Black,Color.Red,Color.Blue,Color.Green,Color.Orange,Color.Brown,Color.DarkBlue};

        //字体列表,用户验证码
        string[] font = {"Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh","PMingLiU", "Impact" };

        //字体列表,用户验证码,这里你可以需要可以增加中文字
        char[] characters = {'1','2', '3', '4', '5', '6', '7', '8', '9','0', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y','Z'};
        Random rnd = new Random();
        //生成验证码字符串
        for (int i = 0; i < 4; i++) {
            chkCode += characters[rnd.Next(characters.Length)];
        }

        //创建画板开始要画验证码了
        Bitmap bmp = new Bitmap(80,20);//创建了一个80*20的图片
        Graphics g = Graphics.FromImage(bmp);
        g.Clear(Color.White);//吧这个图片画面全部清空

        for (int i = 0; i < 3; i++) {
            int x1 = rnd.Next(80);
            int y1 = rnd.Next(20);
            int x2 = rnd.Next(80);
            int y2 = rnd.Next(20);

            Color clr = color[rnd.Next(color.Length)];
            g.DrawLine(new Pen(clr),x1,y1,x2,y2);//在上面画上干扰的线 一共画了3条
        }

        for(int i = 0; i < chkCode.Length;i ++){
            string fnt = font[rnd.Next(font.Length)];
            Font ft = new Font(fnt, 11);
            Color clr = color[rnd.Next(color.Length)];
            g.DrawString(chkCode[i].ToString(),ft, new SolidBrush(clr), (float)i * 20 + 6, (float)2);//画上验证码
        }

        for (int i = 0; i < 50; i++) {
            int x = rnd.Next(bmp.Width);
            int y = rnd.Next(bmp.Height);
            Color clr = color[rnd.Next(color.Length)];
            bmp.SetPixel(x, y, clr);
        }

        Response.Buffer = true;
        Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
        Response.Expires = 0;
        Response.AppendHeader("Pragma","No-Cache");

        MemoryStream ms = new MemoryStream();
        try
        {
            bmp.Save(ms, ImageFormat.Png);
            Response.ClearContent();
            Response.BinaryWrite(ms.ToArray());//以二进制流的形式吧验证码输出到页面上
        }
        finally {
            bmp.Dispose();
            g.Dispose();
        }
    }

 

posted @ 2013-01-16 14:13  唯吴独尊  阅读(777)  评论(1编辑  收藏  举报