C#生成随机验证码代码分享
使用YZMHelper帮助类即可
usingSystem; usingSystem.Web; usingSystem.Drawing; usingSystem.Security.Cryptography;
namespaceProjectWenDangManage.Framework { ///<summary> ///验证码类 ///</summary> publicclassRand { #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 }
///<summary> ///验证图片类 ///</summary> publicclassYZMHelper { #region私有字段 privatestringtext; privateBitmapimage; privateintletterCount=4; //验证码位数 privateintletterWidth=16; //单个字体的宽度范围 privateintletterHeight=20;//单个字体的高度范围 privatestaticbyte[]randb=newbyte[4]; privatestaticRNGCryptoServiceProviderrand=newRNGCryptoServiceProvider(); privateFont[]fonts= { newFont(newFontFamily("TimesNewRoman"),10+Next(1),System.Drawing.FontStyle.Regular), newFont(newFontFamily("Georgia"),10+Next(1),System.Drawing.FontStyle.Regular), newFont(newFontFamily("Arial"),10+Next(1),System.Drawing.FontStyle.Regular), newFont(newFontFamily("ComicSansMS"),10+Next(1),System.Drawing.FontStyle.Regular) }; #endregion
#region公有属性 ///<summary> ///验证码 ///</summary> publicstringText { get{returnthis.text;} }
///<summary> ///验证码图片 ///</summary> publicBitmapImage { get{returnthis.image;} } #endregion
#region构造函数 publicYZMHelper() { HttpContext.Current.Response.Expires=0; HttpContext.Current.Response.Buffer=true; HttpContext.Current.Response.ExpiresAbsolute=DateTime.Now.AddSeconds(-1); HttpContext.Current.Response.AddHeader("pragma","no-cache"); HttpContext.Current.Response.CacheControl="no-cache"; this.text=Rand.Number(4); CreateImage(); } #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> publicvoidCreateImage() { intint_ImageWidth=this.text.Length*letterWidth; Bitmapimage=newBitmap(int_ImageWidth,letterHeight); Graphicsg=Graphics.FromImage(image); g.Clear(Color.White); for(inti=0;i<2;i++) { intx1=Next(image.Width-1); intx2=Next(image.Width-1); inty1=Next(image.Height-1); inty2=Next(image.Height-1); g.DrawLine(newPen(Color.Silver),x1,y1,x2,y2); } int_x=-12,_y=0; for(intint_index=0;int_index<this.text.Length;int_index++) { _x+=Next(12,16); _y=Next(-2,2); stringstr_char=this.text.Substring(int_index,1); str_char=Next(1)==1?str_char.ToLower():str_char.ToUpper(); BrushnewBrush=newSolidBrush(GetRandomColor()); PointthePos=newPoint(_x,_y); g.DrawString(str_char,fonts[Next(fonts.Length-1)],newBrush,thePos); } for(inti=0;i<10;i++) { intx=Next(image.Width-1); inty=Next(image.Height-1); image.SetPixel(x,y,Color.FromArgb(Next(0,255),Next(0,255),Next(0,255))); } image=TwistImage(image,true,Next(1,3),Next(4,6)); g.DrawRectangle(newPen(Color.LightGray,1),0,0,int_ImageWidth-1,(letterHeight-1)); this.image=image; }
///<summary> ///字体随机颜色 ///</summary> publicColorGetRandomColor() { RandomRandomNum_First=newRandom((int)DateTime.Now.Ticks); System.Threading.Thread.Sleep(RandomNum_First.Next(50)); RandomRandomNum_Sencond=newRandom((int)DateTime.Now.Ticks); 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; returnColor.FromArgb(int_Red,int_Green,int_Blue); }
///<summary> ///正弦曲线Wave扭曲图片 ///</summary> ///<paramname="srcBmp">图片路径</param> ///<paramname="bXDir">如果扭曲则选择为True</param> ///<paramname="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param> ///<paramname="dPhase">波形的起始相位,取值区间[0-2*PI)</param> publicSystem.Drawing.BitmapTwistImage(BitmapsrcBmp,boolbXDir,doubledMultValue,doubledPhase) { doublePI=6.283185307179586476925286766559; 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 } }