画验证码

 protected void Page_Load(object sender, EventArgs e)
    {
        //调用函数将验证码生成图片
        this.CreateCheckCodeImage(GenerateCheckCode());
    }


    private string GenerateCheckCode()
    {  //产生五位的随机字符串
        int number;
        char code;
        string checkCode = String.Empty;

        System.Random random = new Random();

        for (int i = 0; i < 5; i++)
        {
            number = random.Next();

            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10));
            else
                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;

        Session["CheckCode"] = checkCode;
        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 18.5)), 28);
        Graphics g = Graphics.FromImage(image);

        try
        {
            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            g.Clear(Color.AntiqueWhite);

            //画图片的背景噪音线
            for (int i = 0; i < 10; 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.Silver), x1, y1, x2, y2);
            }

            Font font = new System.Drawing.Font("Arial", 18, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            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();
        }
    }

    private string GenCode(int num)
    {
        //string str = "的一是在不123456789了Q有和人这Q中大为W上个国我以要他时来E用ASDFGHJKLIUYTREWQZXCVBNM3们生到作地R于出就分对成会可主发年动同工也能下2过子2说产43种ASDFGHJKLIUYTREWQZXCVBNM3面而方后多定行学法0所民得经十三之进着等部度sASDFGHJKLIUYTREWQZXCVBNM3家电力里如水化高自二k123456789q加量都两体制机9当使点从业1本去把性3好应开它E合R还因由其D些然前外天政ASDFGHJKLIUYTREWQZXCVBNM3W四日那社E义事平SWQ形RFE相a全h表间样与关j各重新线内数正心反8你明l看原又么z利比或T但质123456789气第4向道命W3此变43条只DF没结0S解a问A意建8月公0无7系军很情AUF者4W最立代想D1已L通G并提7g直4L34题H党123456789程展五U3果料U象员革4位入常文2总次品式活设U及AY管A特件长求w老头基资5边流2路F级S少图3山统接知5TK较S将0组3见计F别她手5角期b根0论ASDFGHJKLIUYTREWQZXCVBNM3油思s术极交受U123456789联20什认六共S权F收asdecvrrtfghujnmkiolpz证改F清D己美4再采转更7单SD风5切U8打白J2教速花带安IM场123456789身车J例真务具万每目至达G走积r,示345议声U报N斗完类0八离ASDFGHJKLIUYTREWQ123456789ZXCVBNM3华名确A才SS科张CDXG信U马节话XZ米U整空Z元Y况D今集a温传土许步pGBY群广J石记asdecvrrtfghujnmk123456789iolpz需段H4研界拉J林律叫K且究O观越H织K6装U影casdecvr123456789rtfghujnmkiolpzL算低持v音众o3书t布A复TV容儿8际商Z非验连断HJ深难近矿千周委素M技备半办V青VT5省PD列n习响B约s支般史d感I劳便团9往5酸历市克何除消构府u称太准精值号Zi率族G维XB划选标C写存候毛3亲快2效M斯Masdecvrrtfghujnmkiolpz3院C查江4型眼5王4B按格5养N易5置M派5层片U始C却专状育7厂U京asdecvrrtfghujnmkiolpz识7适属圆8包火住调m满县局7照参红细引听该铁价严";
        string str = "123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";//去掉的O容易混淆的字母
        char[] chastr = str.ToCharArray();
        // string[] source ={ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#", "$", "%", "&", "@" };
        string code = "";
        Random rd = new Random();
        int i;
        for (i = 0; i < num; i++)
        {
            //code += source[rd.Next(0, source.Length)];
            code += str.Substring(rd.Next(0, str.Length), 1);

        }
        return code;


    }

 

前台调用时图片地址则可写画验证码的页字(“~/....aspx”);

换一张:

<a href="javascript:document.getElementById('ValidateCodeImage').src='ValidateCode.aspx?'+new Date;void(0);">
                                                   换一张
                                                   </a>

 

posted @ 2013-06-26 19:21  爱生活,爱编程  阅读(340)  评论(0编辑  收藏  举报