您好,登錄后才能下訂單哦!
Random2Verify類 , 隨機產生純數字/純字母/數字加字母2中方式的驗證碼.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace Image2VerifyLib.com { /// <summary> /// 隨機生成驗證碼數據 /// </summary> internal sealed class Random2Verify { #region 生成隨機數字 /// <summary> /// 生成隨機數字 /// </summary> /// <param name="length">生成長度</param> public static string Number(int Length) { return Number(Length, false); } /// <summary> /// 生成隨機數字 /// </summary> /// <param name="Length">生成長度</param> /// <param name="Sleep">是否要在生成前將當前線程阻止以避免重復</param> public static string Number(int Length, bool Sleep) { if (Sleep) System.Threading.Thread.Sleep(3); string result = ""; System.Random random = new Random(); for (int i = 0; i < Length; i++) { result += random.Next(10).ToString(); } return result; } #endregion #region 生成隨機字母與數字 /// <summary> /// 生成隨機字母與數字 /// </summary> /// <param name="IntStr">生成長度</param> public static string Str(int Length) { return Str(Length, false); } /// <summary> /// 生成隨機字母與數字 /// </summary> /// <param name="Length">生成長度</param> /// <param name="Sleep">是否要在生成前將當前線程阻止以避免重復</param> public static string Str(int Length, bool Sleep) { if (Sleep) System.Threading.Thread.Sleep(3); char[] Pattern = new char[] { '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 result = ""; int n = Pattern.Length; System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < Length; i++) { int rnd = random.Next(0, n); result += Pattern[rnd]; } return result; } #endregion #region 生成隨機純字母隨機數 /// <summary> /// 生成隨機純字母隨機數 /// </summary> /// <param name="IntStr">生成長度</param> public static string Str_char(int Length) { return Str_char(Length, false); } /// <summary> /// 生成隨機純字母隨機數 /// </summary> /// <param name="Length">生成長度</param> /// <param name="Sleep">是否要在生成前將當前線程阻止以避免重復</param> public static string Str_char(int Length, bool Sleep) { if (Sleep) System.Threading.Thread.Sleep(3); char[] Pattern = new char[] { '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 result = ""; int n = Pattern.Length; System.Random random = new Random(~unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < Length; i++) { int rnd = random.Next(0, n); result += Pattern[rnd]; } return result; } #endregion } }
核心類Image2VerifyTool:
using System; using System.Security.Cryptography; using System.Drawing; using Image2VerifyLib.com; using System.ComponentModel; using System.Drawing.Drawing2D; namespace Image2VerifyLib { /// <summary> /// 驗證碼生成器 /// </summary> public sealed class Image2VerifyTool { #region 私有字段 private string text = String.Empty; private Bitmap p_w_picpath = null; private readonly int letterCount = 4; //驗證碼位數 private readonly int letterWidth = 16; //單個字體的寬度范圍 private readonly int letterHeight = 20; //單個字體的高度范圍 private static byte[] randb = new byte[4]; private static RNGCryptoServiceProvider rand = new RNGCryptoServiceProvider(); private readonly Color background_color = Color.White;//背景顏色 private Font[] fonts = { new Font(new FontFamily("Times New Roman"),10 +Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold), new Font(new FontFamily("Georgia"), 10 + Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold), new Font(new FontFamily("Arial"), 10 + Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold), new Font(new FontFamily("Comic Sans MS"), 10 + Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold), new Font(new FontFamily("Microsoft YaHei"), 10 + Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold), new Font(new FontFamily("Verdana"), 10 + Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold), new Font(new FontFamily("Tahoma"), 10 + Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold) }; #endregion #region 公有屬性 /// <summary> /// 驗證碼 /// </summary> public string Text { get { return this.text; } } /// <summary> /// 驗證碼位數 /// </summary> public int LetterCount { get { return this.letterCount; } } #endregion #region 構造函數 /// <summary> /// /// </summary> /// <param name="background_color">驗證碼背景色</param> /// <param name="letterCount">驗證碼位數</param> /// <param name="letterWidth">單個字體的寬度范圍</param> /// <param name="letterHeight">單個字體的高度范圍</param> public Image2VerifyTool(Color background_color, int letterCount = 4, int letterWidth = 16, int letterHeight = 20) { this.background_color = background_color; this.letterCount = letterCount; this.letterWidth = letterWidth; this.letterHeight = letterHeight; } #endregion #region 生成驗證碼 /// <summary> /// 生成圖片驗證碼 /// </summary> /// <param name="type">驗證碼類型</param> /// <returns></returns> public Bitmap CreateVerify(Type2Verfy type) { switch (type) { case Type2Verfy.Number: this.text = Random2Verify.Number(this.letterCount); break; case Type2Verfy.Letter: this.text = Random2Verify.Str_char(this.letterCount); break; case Type2Verfy.Number_Letter: this.text = Random2Verify.Str(this.letterCount); break; default: this.text = Random2Verify.Str(this.letterCount); break; } this.CreateImage(); return this.p_w_picpath; } #endregion #region 私有方法 /// <summary> /// 獲得下一個隨機數 /// </summary> /// <param name="max">最大值</param> private static int Next(int max) { rand.GetBytes(randb); int value = BitConverter.ToInt32(randb, 0); value = value % (max + 1); if (value < 0) value = -value; return value; } /// <summary> /// 獲得下一個隨機數 /// </summary> /// <param name="min">最小值</param> /// <param name="max">最大值</param> private static int Next(int min, int max) { int value = Next(max - min) + min; return value; } #endregion #region 公共方法 /// <summary> /// 繪制驗證碼 /// </summary> private void CreateImage() { int int_ImageWidth = this.text.Length * letterWidth; Bitmap p_w_picpath = new Bitmap(int_ImageWidth, letterHeight); Graphics g = Graphics.FromImage(p_w_picpath); g.Clear(this.background_color); int i = 0; for (i = 0; i < 3; i++) { int x1 = Next(p_w_picpath.Width); int x2 = Next(p_w_picpath.Width); int y1 = Next(p_w_picpath.Height); int y2 = Next(p_w_picpath.Height); g.DrawLine(new Pen(GetRandomColor(false), this.Pen_Random_Width), x1, y1, x2, y2); } int _x = -12, _y = 0; for (int int_index = 0; int_index < this.text.Length; int_index++) { _x += Next(14, 18); _y = Next(-1, 0); string str_char = this.text.Substring(int_index, 1); str_char = Next(1) == 1 ? str_char.ToLower() : str_char.ToUpper(); Brush newBrush = new LinearGradientBrush(new Rectangle(_x, _y, p_w_picpath.Width, p_w_picpath.Height), GetRandomColor(true), GetRandomColor(true),1.2f,true); Point thePos = new Point(_x, _y); g.DrawString(str_char, fonts[Next(fonts.Length - 1)] , newBrush, thePos); } //噪點 for (i = 0; i < 15; i++) { int x1 = Next(p_w_picpath.Width - 1); int y1 = Next(p_w_picpath.Height - 1); Pen p = new Pen(GetRandomColor(false), Next(1, 2)); g.DrawRectangle(p, x1, y1, 1, 1); } p_w_picpath = TwistImage(p_w_picpath, true, Next(1, 3), Next(4, 5)); //g.DrawRectangle(new Pen(this.background_color, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1)); this.p_w_picpath = p_w_picpath; } /// <summary> /// 字體隨機顏色 /// </summary> private Color GetRandomColor( Boolean is_code = true ) { Random RandomNum_First = new Random(Guid.NewGuid().GetHashCode()); Random RandomNum_Sencond = new Random(Guid.NewGuid().GetHashCode()); int int_Red = RandomNum_First.Next(180); int int_Green = RandomNum_Sencond.Next(180); int int_Blue = (int_Red + int_Green > 300) ? 0 : 400 - int_Red - int_Green; int_Blue = (int_Blue > 255) ? 255 : int_Blue; if (is_code) return Color.FromArgb(255, int_Red, int_Green, int_Blue); else { //Random rand = new Random(Guid.NewGuid().GetHashCode()); return Color.FromArgb( Next(120,200) , int_Red, int_Green, int_Blue); } } /// <summary> /// pen的隨機寬度 /// </summary> private int Pen_Random_Width { get { //Random rand = new Random(Guid.NewGuid().GetHashCode()); return Next(1, 3); } } /// <summary> /// 正弦曲線Wave扭曲圖片 /// </summary> /// <param name="srcBmp">圖片路徑</param> /// <param name="bXDir">如果扭曲則選擇為True</param> /// <param name="nMultValue">波形的幅度倍數,越大扭曲的程度越高,一般為3</param> /// <param name="dPhase">波形的起始相位,取值區間[0-2*PI)</param> private Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase) { double PI = Math.PI*2.0; Bitmap destBmp = new Bitmap(srcBmp.Width, srcBmp.Height); Graphics graph = Graphics.FromImage(destBmp); graph.FillRectangle(new SolidBrush(Color.White), 0, 0, destBmp.Width, destBmp.Height); graph.Dispose(); double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width; for (int i = 0; i < destBmp.Width; i++) { for (int j = 0; j < destBmp.Height; j++) { double dx = 0; dx = bXDir ? (PI * (double)j) / dBaseAxisLen : (PI * (double)i) / dBaseAxisLen; dx += dPhase; double dy = Math.Sin(dx); int nOldX = 0, nOldY = 0; nOldX = bXDir ? i + (int)(dy * dMultValue) : i; nOldY = bXDir ? j : j + (int)(dy * dMultValue); Color color = srcBmp.GetPixel(i, j); if (nOldX >= 0 && nOldX < destBmp.Width && nOldY >= 0 && nOldY < destBmp.Height) { destBmp.SetPixel(nOldX, nOldY, color); } } } srcBmp.Dispose(); return destBmp; } #endregion } /// <summary> /// 驗證碼類型的枚舉 /// </summary> public enum Type2Verfy : uint { [Description("純數字")] Number = 0, [Description("純字母")] Letter = 1, [Description("數字加字母")] Number_Letter = 2 } }
測試(winform)
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Image2VerifyLib; namespace Image2VerifyTest { public partial class Form1 : Form { private Image2VerifyTool img2Verify = null; private string verify2code = string.Empty; public Form1() { InitializeComponent(); img2Verify = new Image2VerifyTool(Color.Violet,5,20,25); verify2code = this.create_img2verify(); } private string create_img2verify() { Bitmap p_w_picpath = img2Verify.CreateVerify(Type2Verfy.Number_Letter);//創建數字字母混合型驗證碼 this.pictureBox1.Image = p_w_picpath; return img2Verify.Text.ToLower(); } private void button1_Click(object sender, EventArgs e) { string inter_str = this.textBox1.Text.Trim().ToLower(); if (inter_str.Length == 0) { MessageBox.Show("請先填寫驗證碼"); } else { if (inter_str.Length != img2Verify.LetterCount || inter_str != verify2code) { MessageBox.Show("驗證碼錯誤"); verify2code = this.create_img2verify(); } else { MessageBox.Show("恭喜,通過驗證"); } } } private void button2_Click(object sender, EventArgs e) { verify2code = this.create_img2verify(); } } }
new Image2VerifyTool(Color.Violet,5,20,25);構造函數參數解釋
第一個 : 驗證碼背景色
第二個 : 產生幾位的驗證碼(本次5位)
第三個 : 每一位驗證碼的寬度
第四個 : 每一位驗證碼的高度
其中 : Bitmap p_w_picpath = Image2VerifyTool.CreateVerify(Type2Verfy.Number_Letter);//創建數字字母混合型驗證碼得到一個字母與數字混合型的圖片
驗證碼的獲取 : Image2VerifyTool.Text
驗證碼類型參見:
/// <summary> /// 驗證碼類型的枚舉 /// </summary> public enum Type2Verfy : uint { [Description("純數字")] Number = 0, [Description("純字母")] Letter = 1, [Description("數字加字母")] Number_Letter = 2 }
結果:
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。