天天看點

使用者登陸的驗證碼的制作

添加命名空間:

using System.Drawing;

 驗證碼的生成:

protected void FormCheck()

    {

        //////先得到驗證碼的内容并且存放到會話中

        Random rand = new Random();

        int len = rand.Next(4, 6);//随機獲得驗證碼的長度4-6位

        char[] str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();//将候選字元放入字元數組中

        System .Text .StringBuilder code=new System.Text.StringBuilder ();//用來儲存顯示的字元内容

        for (int i=0;i<len;i++)

        {

        code .Append (str [rand .Next (str.Length )]);

        }

        this.Session ["result"]=code.ToString () ;//将驗證碼存放到會話中

        ///////得到圖像的大小

        Size imageSize = new Size();

        Font myFont = new Font("arial black", 20); //字型

        using (Bitmap bmp = new Bitmap(20, 15))

        { using (Graphics g=Graphics .FromImage (bmp ))

         SizeF size=g.MeasureString (code.ToString () ,myFont,1000 );

            imageSize .Width =(int)size .Width +6;//得到高度和寬的

            imageSize .Height =(int)size .Height +5;

        /////建立驗證碼的圖像

        using (Bitmap bmp=new Bitmap (imageSize .Width ,imageSize .Height ))

        using (Graphics g=Graphics .FromImage (bmp ))

            g.Clear(Color .White );

            g.DrawString  (code.ToString () ,myFont ,Brushes .Black ,new RectangleF (0,0,imageSize.Width ,imageSize .Height ));

        int num = imageSize.Width * imageSize.Height * 30 / 100;

        for (int iCount = 0; iCount < num; iCount++)

            // 在随機的位置使用随機的顔色設定圖檔的像素

            int x = rand.Next(imageSize.Width);

            int y = rand.Next(imageSize.Height);

            int r = rand.Next(255);

            int g = rand.Next(255);

            int b = rand.Next(255);

            Color c = Color.FromArgb(r, g, b);

            bmp.SetPixel(x, y, c);

        }//for                // 輸出圖檔

        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png );

        this.Response.ContentType = "image/png";

        ms.WriteTo(this.Response.OutputStream);

        ms.Close();

    }

///

        /// 檢查指定的文本是否比對驗證碼

        ///

        /// 要判斷的文本

        /// 是否比對

        public static bool CheckCode( string text )

        {

        string txt = System.Web.HttpContext.Current.Session["checkcode"] as string ;

        return text == txt ;

        }

    本文轉自 陳敬(Cathy) 部落格園部落格,原文連結:http://www.cnblogs.com/janes/archive/2008/07/23/1249646.html,如需轉載請自行聯系原作者

繼續閱讀