Random2Verify类 , 随机产生纯数字/纯字母/数字加字母2中方式的验证码.
在网站设计、成都做网站中从网站色彩、结构布局、栏目设置、关键词群组等细微处着手,突出企业的产品/服务/品牌,帮助企业锁定精准用户,提高在线咨询和转化,使成都网站营销成为有效果、有回报的无锡营销推广。创新互联建站专业成都网站建设10年了,客户满意度97.8%,欢迎成都创新互联客户联系。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace Image2VerifyLib.com { ////// 随机生成验证码数据 /// internal sealed class Random2Verify { #region 生成随机数字 ////// 生成随机数字 /// /// 生成长度 public static string Number(int Length) { return Number(Length, false); } ////// 生成随机数字 /// /// 生成长度 /// 是否要在生成前将当前线程阻止以避免重复 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 生成随机字母与数字 ////// 生成随机字母与数字 /// /// 生成长度 public static string Str(int Length) { return Str(Length, false); } ////// 生成随机字母与数字 /// /// 生成长度 /// 是否要在生成前将当前线程阻止以避免重复 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 生成随机纯字母随机数 ////// 生成随机纯字母随机数 /// /// 生成长度 public static string Str_char(int Length) { return Str_char(Length, false); } ////// 生成随机纯字母随机数 /// /// 生成长度 /// 是否要在生成前将当前线程阻止以避免重复 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 { ////// 验证码生成器 /// 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 公有属性 ////// 验证码 /// public string Text { get { return this.text; } } ////// 验证码位数 /// public int LetterCount { get { return this.letterCount; } } #endregion #region 构造函数 ////// /// /// 验证码背景色 /// 验证码位数 /// 单个字体的宽度范围 /// 单个字体的高度范围 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 生成验证码 ////// 生成图片验证码 /// /// 验证码类型 ///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 私有方法 /// /// 获得下一个随机数 /// /// 最大值 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; } ////// 获得下一个随机数 /// /// 最小值 /// 最大值 private static int Next(int min, int max) { int value = Next(max - min) + min; return value; } #endregion #region 公共方法 ////// 绘制验证码 /// 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; } ////// 字体随机颜色 /// 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); } } ////// pen的随机宽度 /// private int Pen_Random_Width { get { //Random rand = new Random(Guid.NewGuid().GetHashCode()); return Next(1, 3); } } ////// 正弦曲线Wave扭曲图片 /// /// 图片路径 /// 如果扭曲则选择为True /// 波形的幅度倍数,越大扭曲的程度越高,一般为3 /// 波形的起始相位,取值区间[0-2*PI) 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 } ////// 验证码类型的枚举 /// 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
验证码类型参见:
////// 验证码类型的枚举 /// public enum Type2Verfy : uint { [Description("纯数字")] Number = 0, [Description("纯字母")] Letter = 1, [Description("数字加字母")] Number_Letter = 2 }
结果: