1. 程式人生 > >C#驗證碼的建立和使用

C#驗證碼的建立和使用

先新增一個驗證碼類ValidateCode

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

namespace 驗證碼生成和使用
{
    public class ValidateCode
    {
        public ValidateCode()
        {
        }
        /// <summary>
        /// 驗證碼的最大長度
        /// </summary>
        public int MaxLength
        {
            get { return 10; }
        }
        /// <summary>
        /// 驗證碼的最小長度
        /// </summary>
        public int MinLength
        {
            get { return 1; }
        }
        /// <summary>
        /// 生成驗證碼
        /// </summary>
        /// <param name="length">指定驗證碼的長度</param>
        /// <returns></returns>
        public string CreateValidateCode(int length)
        {
            int[] randMembers = new int[length];
            int[] validateNums = new int[length];
            string validateNumberStr = "";
            //生成起始序列值
            int seekSeek = unchecked((int)DateTime.Now.Ticks);
            Random seekRand = new Random(seekSeek);
            int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
            int[] seeks = new int[length];
            for (int i = 0; i < length; i++)
            {
                beginSeek += 10000;
                seeks[i] = beginSeek;
            }
            //生成隨機數字
            for (int i = 0; i < length; i++)
            {
                Random rand = new Random(seeks[i]);
                int pownum = 1 * (int)Math.Pow(10, length);
                randMembers[i] = rand.Next(pownum, Int32.MaxValue);
            }
            //抽取隨機數字
            for (int i = 0; i < length; i++)
            {
                string numStr = randMembers[i].ToString();
                int numLength = numStr.Length;
                Random rand = new Random();
                int numPosition = rand.Next(0, numLength - 1);
                validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
            }
            //生成驗證碼
            for (int i = 0; i < length; i++)
            {
                validateNumberStr += validateNums[i].ToString();
            }
            return validateNumberStr;
        }
        /// <summary>
        /// 建立驗證碼的圖片
        /// </summary>
        /// <param name="context">要輸出到的page物件</param>
        /// <param name="validateNum">驗證碼</param>
        public void CreateValidateGraphic(string validateCode, HttpContext context)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成隨機生成器
                Random random = new Random();
                //清空圖片背景色
                g.Clear(Color.White);
                //畫圖片的干擾線
                for (int i = 0; i < 25; 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 Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 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);
                //儲存圖片資料
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //輸出圖片流
                context.Response.Clear();
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(stream.ToArray());
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        /// <summary>
        /// 得到驗證碼圖片的長度
        /// </summary>
        /// <param name="validateNumLength">驗證碼的長度</param>
        /// <returns></returns>
        public static int GetImageWidth(int validateNumLength)
        {
            return (int)(validateNumLength * 12.0);
        }
        /// <summary>
        /// 得到驗證碼的高度
        /// </summary>
        /// <returns></returns>
        public static double GetImageHeight()
        {
            return 22.5;
        }

        /// <summary>
        /// 建立驗證碼的圖片
        /// </summary>
        /// <param name="containsPage">要輸出到的page物件</param>
        /// <param name="validateNum">驗證碼</param>
        public byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成隨機生成器
                Random random = new Random();
                //清空圖片背景色
                g.Clear(Color.White);
                //畫圖片的干擾線
                for (int i = 0; i < 25; 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 Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 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);
                //儲存圖片資料
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //輸出圖片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}

注意一點是,需要引用名稱空間:

using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Web;------這個需要先在新增引用裡面的程式集裡引用到

上面是生成驗證碼的類,下面是使用驗證碼的窗體:

如下四個控制元件

private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Button btnLogin;
private System.Windows.Forms.Label label1;

窗體的程式碼:

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace 驗證碼生成和使用
{
    public partial class frmMain : Form
    {
        ValidateCode code = new ValidateCode();//例項化生成驗證碼的類
        private string vcode = string.Empty;//宣告儲存驗證碼的字串變數
        public frmMain()
        {
            InitializeComponent();
            ShowCode();//呼叫生成驗證碼的方法
        }
        //生成驗證碼的方法
        private void ShowCode()
        {
            vcode = code.CreateValidateCode(4);//把生成的驗證碼賦值給變數
            byte[] buffer = code.CreateValidateGraphic(vcode);//把字串轉成位元組流
            pictureBox1.Image = ByteToImage(buffer);//把位元組流轉成圖片顯示在窗體中的pictureBox1控制元件
        }
        /// <summary>
        /// 位元組流轉成圖片
        /// </summary>
        /// <param name="buffer">需要轉換的位元組流</param>
        /// <returns>返回生成圖片</returns>
        private Image ByteToImage(byte[] buffer)
        {
            MemoryStream ms = new MemoryStream(buffer);
            return Image.FromStream(ms, true);
        }
        //登入按鈕驗證輸入的驗證碼是否正確
        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() != vcode)
            {
                this.Text = "驗證碼錯誤";
                textBox1.Focus();//輸入錯誤,輸入框獲取焦點
            }
            else
            {
                this.Text = "驗證碼正確";
            }
        }
        //看不清換一張,重新呼叫一下生成驗證碼的方法
        private void label1_Click(object sender, EventArgs e)
        {
            ShowCode();
        }
    }
}

每步都有註釋,主要點在於位元組流轉換成圖片的方法