自己寫的一個圖形驗證碼頁面(Asp.Net2.0通過)

來源:互聯網
上載者:User
本文範例程式碼
項目需要,要在首頁登入介面添加一個圖形驗證碼,趕時髦吧,網上一搜,特別多,找了幾個,都不太滿意。主要問題是大部分代碼產生的圖片寬度不唯一,頁面配置不容易控制,其次是顏色單一,有些又過於抽象,不仔細看很容易弄錯。針對特定的客戶,我只需要“圖片”長寬固定,顏色多樣的數字圖形驗證碼,借鑒網上的現有代碼,自己操刀完成,以下是:

原理不複雜,就是把網頁當畫布,運用各色畫筆,在特定地區內畫出數字,然後以特定格式(本例為PNG格式)發回用戶端,在IE中顯示為"圖片",用於驗證的字串存於Session中。

主要代碼如下://   產生隨機數字字串
public string GetRandomNumberString(int int_NumberLength)
{
    string str_Number = string.Empty;
     Random theRandomNumber = new Random();

    for (int int_index = 0; int_index < int_NumberLength; int_index++)
         str_Number += theRandomNumber.Next(10).ToString();

    return str_Number;
}

產生隨機顏色public Color GetRandomColor()
{
     Random RandomNum_First = new Random((int)DateTime.Now.Ticks);
    //   對於C#的隨機數,沒什麼好說的
     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 * 13;
     Random newRandom = new Random();
    //   圖高20px
     Bitmap theBitmap = new Bitmap(int_ImageWidth, 20);
     Graphics theGraphics = Graphics.FromImage(theBitmap);
    //   白色背景
     theGraphics.Clear(Color.White);
    //   灰色邊框
     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++)
    {            
        string str_char = str_ValidateCode.Substring(int_index, 1);
         Brush newBrush = new SolidBrush(GetRandomColor());
         Point thePos = new Point(int_index * 13 + 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());
     theGraphics.Dispose();
     theBitmap.Dispose();
     Response.End();
}

最後在Page_Load中調用以上代碼

private void Page_Load(object sender, System.EventArgs e)
{      
    if(!IsPostBack)
    {
        //   4位元字的驗證碼
        string str_ValidateCode = GetRandomNumberString(4);
        //   用於驗證的Session
         Session["ValidateCode"] = str_ValidateCode;
         CreateImage(str_ValidateCode);
     }
}

使用的時候在頁面中加入一個Image,將圖片路徑改為ValidateCode.aspx的相對路徑即可

<img src="ValidateCode.aspx" />

在需要驗證的地方填入如下代碼:if (TextBox1.Text == Session["ValidateCode"].ToString())
{
     TextBox1.Text = "正確!";
}
else
     TextBox1.Text = "錯誤!";

OK,基本搞定,總結一下:
優點:1. 簡單明了,適於簡單運用
          2. 介面友好,圖片長寬格式固定
缺點:1. 如果有多個頁面都需要此驗證碼,則會導致Session被其它頁面重寫的情況,可以考慮指定具體Session值為效驗值
          2. 暫時只支援數字,不過更改GetRandomNumberString()中的代碼可以實現指定字元集的隨機字串
          3. 頁面重新整理後驗證碼隨之改變

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.