分享一個驗證碼程序,字母和數字

      驗證碼程序的圖片是有1--10張圖片,系統自動選擇,是字母和數字一起的一個驗證碼。很不錯的。拿出來和大家分享一下。

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;

public partial class Ajax_Login_Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            this.GenImg(this.GetCode(4));
        }
    }
    //產生隨機字符串
    private string GetCode(int num)
    {
        string[] source ={ "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        string code = "";
        Random rd = new Random();
        for (int i = 0; i < num; i++)
        {
            code += source[rd.Next(0, source.Length)];
        }
        return code;
    }

    //生成圖片
    private void GenImg(string code)
    {
        Random rd = new Random();
        Bitmap myPalette = new Bitmap(120, 60);                                          //定義一個畫板
        Graphics gh = Graphics.FromImage(myPalette);                                //在畫板上定義繪圖的實例
        Rectangle rc = new Rectangle(0, 0, 120, 60);                                 //定義一個矩形
        String picPath = Server.MapPath("pic/bg" + rd.Next(1, 4).ToString().Trim() + ".jpg");
        Bitmap imagefile = (Bitmap)System.Drawing.Image.FromFile(picPath, true);                    //得到一張位圖       
        TextureBrush texture = new TextureBrush(imagefile);                                  //以圖片建立繪圖刷
        Color[] fontcolor = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Red, Color.Brown, Color.DarkCyan, Color.Purple };  //定義 8 種顏色
        String[] fontname = { "Verdana", "System", "Comic Sans MS", "Arial", "宋體" };    //定義 5 種字體
        Font myfont;     //字體定義
        SolidBrush mybrush;    //畫筆定義


        gh.FillRectangle(texture, rc);//使用繪圖刷填充矩形,到此得到圖片背景

        for (short i = 0; i <= code.Length - 1; i++)
        {
            myfont = new Font(fontname[rd.Next(0, 5)], 30, FontStyle.Italic);    //隨機字體,42號,斜體
            mybrush = new SolidBrush(fontcolor[rd.Next(0, 8)]); //隨機顏色
            gh.DrawString(code.Substring(i, 1), myfont, mybrush, 3 + (i * 23), rd.Next(1, 8));//在矩形內畫出字符串
        }

 

        myPalette.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//將圖片顯示出來

        Session["ValidateCode"] = code;//將字符串保存到Session中,以便需要時進行驗證

        gh.Dispose();
        myPalette.Dispose();
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章