首页 > 代码库 > C# 验证码
C# 验证码
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 image = 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.image; } #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 image = new Bitmap(int_ImageWidth, letterHeight); Graphics g = Graphics.FromImage(image); g.Clear(this.background_color); int i = 0; for (i = 0; i < 3; i++) { int x1 = Next(image.Width); int x2 = Next(image.Width); int y1 = Next(image.Height); int y2 = Next(image.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, image.Width, image.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(image.Width - 1); int y1 = Next(image.Height - 1); Pen p = new Pen(GetRandomColor(false), Next(1, 2)); g.DrawRectangle(p, x1, y1, 1, 1); } image = TwistImage(image, true, Next(1, 3), Next(4, 5)); //g.DrawRectangle(new Pen(this.background_color, 1), 0, 0, int_ImageWidth - 1, (letterHeight - 1)); this.image = image; } /// <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 image = img2Verify.CreateVerify(Type2Verfy.Number_Letter);//创建数字字母混合型验证码 this.pictureBox1.Image = image; 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 image = Image2VerifyTool.CreateVerify(Type2Verfy.Number_Letter);//创建数字字母混合型验证码得到一个字母与数字混合型的图片
验证码的获取 : Image2VerifyTool.Text
验证码类型参见:
/// <summary> /// 验证码类型的枚举 /// </summary> public enum Type2Verfy : uint { [Description("纯数字")] Number = 0, [Description("纯字母")] Letter = 1, [Description("数字加字母")] Number_Letter = 2 }
结果:
本文出自 “Better_Power_Wisdom” 博客,请务必保留此出处http://aonaufly.blog.51cto.com/3554853/1953094
C# 验证码
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。