C# 验证码
Random2Verify类 , 随机产生纯数字/纯字母/数字加字母2中方式的验证码.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Drawing;namespaceImage2VerifyLib.com{///<summary>///随机生成验证码数据///</summary>internalsealedclassRandom2Verify{#region生成随机数字///<summary>///生成随机数字///</summary>///<paramname="length">生成长度</param>publicstaticstringNumber(intLength){returnNumber(Length,false);}///<summary>///生成随机数字///</summary>///<paramname="Length">生成长度</param>///<paramname="Sleep">是否要在生成前将当前线程阻止以避免重复</param>publicstaticstringNumber(intLength,boolSleep){if(Sleep)System.Threading.Thread.Sleep(3);stringresult="";System.Randomrandom=newRandom();for(inti=0;i<Length;i++){result+=random.Next(10).ToString();}returnresult;}#endregion#region生成随机字母与数字///<summary>///生成随机字母与数字///</summary>///<paramname="IntStr">生成长度</param>publicstaticstringStr(intLength){returnStr(Length,false);}///<summary>///生成随机字母与数字///</summary>///<paramname="Length">生成长度</param>///<paramname="Sleep">是否要在生成前将当前线程阻止以避免重复</param>publicstaticstringStr(intLength,boolSleep){if(Sleep)System.Threading.Thread.Sleep(3);char[]Pattern=newchar[]{'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'};stringresult="";intn=Pattern.Length;System.Randomrandom=newRandom(~unchecked((int)DateTime.Now.Ticks));for(inti=0;i<Length;i++){intrnd=random.Next(0,n);result+=Pattern[rnd];}returnresult;}#endregion#region生成随机纯字母随机数///<summary>///生成随机纯字母随机数///</summary>///<paramname="IntStr">生成长度</param>publicstaticstringStr_char(intLength){returnStr_char(Length,false);}///<summary>///生成随机纯字母随机数///</summary>///<paramname="Length">生成长度</param>///<paramname="Sleep">是否要在生成前将当前线程阻止以避免重复</param>publicstaticstringStr_char(intLength,boolSleep){if(Sleep)System.Threading.Thread.Sleep(3);char[]Pattern=newchar[]{'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'};stringresult="";intn=Pattern.Length;System.Randomrandom=newRandom(~unchecked((int)DateTime.Now.Ticks));for(inti=0;i<Length;i++){intrnd=random.Next(0,n);result+=Pattern[rnd];}returnresult;}#endregion}}
核心类Image2VerifyTool:
usingSystem;usingSystem.Security.Cryptography;usingSystem.Drawing;usingImage2VerifyLib.com;usingSystem.ComponentModel;usingSystem.Drawing.Drawing2D;namespaceImage2VerifyLib{///<summary>///验证码生成器///</summary>publicsealedclassImage2VerifyTool{#region私有字段privatestringtext=String.Empty;privateBitmapp_w_picpath=null;privatereadonlyintletterCount=4;//验证码位数privatereadonlyintletterWidth=16;//单个字体的宽度范围privatereadonlyintletterHeight=20;//单个字体的高度范围privatestaticbyte[]randb=newbyte[4];privatestaticRNGCryptoServiceProviderrand=newRNGCryptoServiceProvider();privatereadonlyColorbackground_color=Color.White;//背景颜色privateFont[]fonts={newFont(newFontFamily("TimesNewRoman"),10+Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold),newFont(newFontFamily("Georgia"),10+Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold),newFont(newFontFamily("Arial"),10+Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold),newFont(newFontFamily("ComicSansMS"),10+Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold),newFont(newFontFamily("MicrosoftYaHei"),10+Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold),newFont(newFontFamily("Verdana"),10+Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold),newFont(newFontFamily("Tahoma"),10+Next(4,8),System.Drawing.FontStyle.Italic|System.Drawing.FontStyle.Bold)};#endregion#region公有属性///<summary>///验证码///</summary>publicstringText{get{returnthis.text;}}///<summary>///验证码位数///</summary>publicintLetterCount{get{returnthis.letterCount;}}#endregion#region构造函数///<summary>//////</summary>///<paramname="background_color">验证码背景色</param>///<paramname="letterCount">验证码位数</param>///<paramname="letterWidth">单个字体的宽度范围</param>///<paramname="letterHeight">单个字体的高度范围</param>publicImage2VerifyTool(Colorbackground_color,intletterCount=4,intletterWidth=16,intletterHeight=20){this.background_color=background_color;this.letterCount=letterCount;this.letterWidth=letterWidth;this.letterHeight=letterHeight;}#endregion#region生成验证码///<summary>///生成图片验证码///</summary>///<paramname="type">验证码类型</param>///<returns></returns>publicBitmapCreateVerify(Type2Verfytype){switch(type){caseType2Verfy.Number:this.text=Random2Verify.Number(this.letterCount);break;caseType2Verfy.Letter:this.text=Random2Verify.Str_char(this.letterCount);break;caseType2Verfy.Number_Letter:this.text=Random2Verify.Str(this.letterCount);break;default:this.text=Random2Verify.Str(this.letterCount);break;}this.CreateImage();returnthis.p_w_picpath;}#endregion#region私有方法///<summary>///获得下一个随机数///</summary>///<paramname="max">最大值</param>privatestaticintNext(intmax){rand.GetBytes(randb);intvalue=BitConverter.ToInt32(randb,0);value=value%(max+1);if(value<0)value=-value;returnvalue;}///<summary>///获得下一个随机数///</summary>///<paramname="min">最小值</param>///<paramname="max">最大值</param>privatestaticintNext(intmin,intmax){intvalue=Next(max-min)+min;returnvalue;}#endregion#region公共方法///<summary>///绘制验证码///</summary>privatevoidCreateImage(){intint_ImageWidth=this.text.Length*letterWidth;Bitmapp_w_picpath=newBitmap(int_ImageWidth,letterHeight);Graphicsg=Graphics.FromImage(p_w_picpath);g.Clear(this.background_color);inti=0;for(i=0;i<3;i++){intx1=Next(p_w_picpath.Width);intx2=Next(p_w_picpath.Width);inty1=Next(p_w_picpath.Height);inty2=Next(p_w_picpath.Height);g.DrawLine(newPen(GetRandomColor(false),this.Pen_Random_Width),x1,y1,x2,y2);}int_x=-12,_y=0;for(intint_index=0;int_index<this.text.Length;int_index++){_x+=Next(14,18);_y=Next(-1,0);stringstr_char=this.text.Substring(int_index,1);str_char=Next(1)==1?str_char.ToLower():str_char.ToUpper();BrushnewBrush=newLinearGradientBrush(newRectangle(_x,_y,p_w_picpath.Width,p_w_picpath.Height),GetRandomColor(true),GetRandomColor(true),1.2f,true);PointthePos=newPoint(_x,_y);g.DrawString(str_char,fonts[Next(fonts.Length-1)],newBrush,thePos);}//噪点for(i=0;i<15;i++){intx1=Next(p_w_picpath.Width-1);inty1=Next(p_w_picpath.Height-1);Penp=newPen(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(newPen(this.background_color,1),0,0,int_ImageWidth-1,(letterHeight-1));this.p_w_picpath=p_w_picpath;}///<summary>///字体随机颜色///</summary>privateColorGetRandomColor(Booleanis_code=true){RandomRandomNum_First=newRandom(Guid.NewGuid().GetHashCode());RandomRandomNum_Sencond=newRandom(Guid.NewGuid().GetHashCode());intint_Red=RandomNum_First.Next(180);intint_Green=RandomNum_Sencond.Next(180);intint_Blue=(int_Red+int_Green>300)?0:400-int_Red-int_Green;int_Blue=(int_Blue>255)?255:int_Blue;if(is_code)returnColor.FromArgb(255,int_Red,int_Green,int_Blue);else{//Randomrand=newRandom(Guid.NewGuid().GetHashCode());returnColor.FromArgb(Next(120,200),int_Red,int_Green,int_Blue);}}///<summary>///pen的随机宽度///</summary>privateintPen_Random_Width{get{//Randomrand=newRandom(Guid.NewGuid().GetHashCode());returnNext(1,3);}}///<summary>///正弦曲线Wave扭曲图片///</summary>///<paramname="srcBmp">图片路径</param>///<paramname="bXDir">如果扭曲则选择为True</param>///<paramname="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>///<paramname="dPhase">波形的起始相位,取值区间[0-2*PI)</param>privateBitmapTwistImage(BitmapsrcBmp,boolbXDir,doubledMultValue,doubledPhase){doublePI=Math.PI*2.0;BitmapdestBmp=newBitmap(srcBmp.Width,srcBmp.Height);Graphicsgraph=Graphics.FromImage(destBmp);graph.FillRectangle(newSolidBrush(Color.White),0,0,destBmp.Width,destBmp.Height);graph.Dispose();doubledBaseAxisLen=bXDir?(double)destBmp.Height:(double)destBmp.Width;for(inti=0;i<destBmp.Width;i++){for(intj=0;j<destBmp.Height;j++){doubledx=0;dx=bXDir?(PI*(double)j)/dBaseAxisLen:(PI*(double)i)/dBaseAxisLen;dx+=dPhase;doubledy=Math.Sin(dx);intnOldX=0,nOldY=0;nOldX=bXDir?i+(int)(dy*dMultValue):i;nOldY=bXDir?j:j+(int)(dy*dMultValue);Colorcolor=srcBmp.GetPixel(i,j);if(nOldX>=0&&nOldX<destBmp.Width&&nOldY>=0&&nOldY<destBmp.Height){destBmp.SetPixel(nOldX,nOldY,color);}}}srcBmp.Dispose();returndestBmp;}#endregion}///<summary>///验证码类型的枚举///</summary>publicenumType2Verfy:uint{[Description("纯数字")]Number=0,[Description("纯字母")]Letter=1,[Description("数字加字母")]Number_Letter=2}}
测试(winform)
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingImage2VerifyLib;namespaceImage2VerifyTest{publicpartialclassForm1:Form{privateImage2VerifyToolimg2Verify=null;privatestringverify2code=string.Empty;publicForm1(){InitializeComponent();img2Verify=newImage2VerifyTool(Color.Violet,5,20,25);verify2code=this.create_img2verify();}privatestringcreate_img2verify(){Bitmapp_w_picpath=img2Verify.CreateVerify(Type2Verfy.Number_Letter);//创建数字字母混合型验证码this.pictureBox1.Image=p_w_picpath;returnimg2Verify.Text.ToLower();}privatevoidbutton1_Click(objectsender,EventArgse){stringinter_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("恭喜,通过验证");}}}privatevoidbutton2_Click(objectsender,EventArgse){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>publicenumType2Verfy:uint{[Description("纯数字")]Number=0,[Description("纯字母")]Letter=1,[Description("数字加字母")]Number_Letter=2}
结果:
附件:http://down.51cto.com/data/2366904声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。