理解C#生成验证码的过程
本文实例为大家介绍了生成验证码的详细过程,供大家参考,具体内容如下
生成验证码的类:
usingSystem; usingSystem.Collections.Generic; usingSystem.Drawing; usingSystem.Text; namespaceControllers.Core.Util { ///<summary> ///验证码 ///</summary> publicclassVerifyCodeHelper:AdminBaseController { #region变量 ///<summary> ///颜色表 ///</summary> privatestaticColor[]colors=newColor[]{ Color.FromArgb(220,20,60), Color.FromArgb(128,0,128), Color.FromArgb(65,105,225), Color.FromArgb(70,130,180), Color.FromArgb(46,139,87), Color.FromArgb(184,134,11), Color.FromArgb(255,140,0), Color.FromArgb(139,69,19), Color.FromArgb(0,191,255), Color.FromArgb(95,158,160), Color.FromArgb(255,20,147), Color.FromArgb(255,165,0)}; ///<summary> ///字体表 ///</summary> privatestaticstring[]fonts=newstring[]{ "Arial", "Verdana", "Georgia", "黑体"}; ///<summary> ///字体大小 ///</summary> privatestaticintfontSize=22; #endregion #region生成验证码图片 ///<summary> ///生成验证码图片 ///</summary> publicstaticBitmapCreateVerifyCodeBmp(outstringcode) { intwidth=120; intheight=40; Bitmapbmp=newBitmap(width,height); Graphicsg=Graphics.FromImage(bmp); Randomrnd=newRandom(); //背景色 g.FillRectangle(newSolidBrush(Color.White),newRectangle(0,0,width,height)); //文字 StringBuildersbCode=newStringBuilder(); for(inti=0;i<4;i++) { stringstr=GetChar(rnd); Fontfont=GetFont(rnd); Colorcolor=GetColor(rnd); g.DrawString(str,font,newSolidBrush(color),newPointF((float)(i*width/4.0),0)); sbCode.Append(str); } code=sbCode.ToString(); //噪音线 for(inti=0;i<10;i++) { intx1=rnd.Next(bmp.Width); intx2=rnd.Next(bmp.Width); inty1=rnd.Next(bmp.Height); inty2=rnd.Next(bmp.Height); Penp=newPen(GetColor(rnd),1); g.DrawLine(p,x1,y1,x2,y2); } //扭曲 bmp=TwistImage(bmp,true,3,rnd.NextDouble()*Math.PI*2); g=Graphics.FromImage(bmp); //噪点 for(inti=0;i<100;i++) { intx1=rnd.Next(bmp.Width); inty1=rnd.Next(bmp.Height); Penp=newPen(GetColor(rnd),1); g.DrawRectangle(p,x1,y1,1,1); } //边框 g.DrawRectangle(newPen(newSolidBrush(Color.FromArgb(153,153,153))),newRectangle(0,0,width-1,height-1)); returnbmp; } #endregion #region获取随机字符 ///<summary> ///获取随机字符 ///</summary> privatestaticstringGetChar(Randomrnd) { intn=rnd.Next(0,61); if(n<=9) { return((char)(48+n)).ToString(); } elseif(n<=35) { return((char)(65+n-10)).ToString(); } else { return((char)(97+n-36)).ToString(); } } #endregion #region获取随机字体 ///<summary> ///获取随机字体 ///</summary> privatestaticFontGetFont(Randomrnd) { returnnewFont(fonts[rnd.Next(0,fonts.Length)],fontSize,FontStyle.Bold); } #endregion #region获取随机颜色 ///<summary> ///获取随机颜色 ///</summary> privatestaticColorGetColor(Randomrnd) { returncolors[rnd.Next(0,colors.Length)]; } #endregion #region正弦曲线Wave扭曲图片 ///<summary> ///正弦曲线Wave扭曲图片(EditBy51aspx.com) ///</summary> ///<paramname="srcBmp">图片路径</param> ///<paramname="bXDir">如果扭曲则选择为True</param> ///<paramname="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param> ///<paramname="dPhase">波形的起始相位,取值区间[0-2*PI)</param> privatestaticSystem.Drawing.BitmapTwistImage(BitmapsrcBmp,boolbXDir,doubledMultValue,doubledPhase) { System.Drawing.BitmapdestBmp=newBitmap(srcBmp.Width,srcBmp.Height); //将位图背景填充为白色 System.Drawing.Graphicsgraph=System.Drawing.Graphics.FromImage(destBmp); graph.FillRectangle(newSolidBrush(System.Drawing.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?(Math.PI*2*(double)j)/dBaseAxisLen:(Math.PI*2*(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); System.Drawing.Colorcolor=srcBmp.GetPixel(i,j); if(nOldX>=0&&nOldX<destBmp.Width &&nOldY>=0&&nOldY<destBmp.Height) { destBmp.SetPixel(nOldX,nOldY,color); } } } returndestBmp; } #endregion } }
验证码页面Action:
publicActionResultVerifyCode() { stringcode; Bitmapbmp=VerifyCodeHelper.CreateVerifyCodeBmp(outcode); Bitmapnewbmp=newBitmap(bmp,108,36); HttpContext.Session["VerifyCode"]=code; Response.Clear(); Response.ContentType="image/bmp"; newbmp.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Bmp); returnView(); }
说明:前台页面为空的cshtml页面,验证码的值放在Session中。
使用验证码的页面:
显示验证码的img:
<imgid="verifyCode"src=""alt="验证码"style="vertical-align:middle;"/>
页面加载完成后,显示验证码(注意,要加上时间戳,不然刷新页面时验证码不刷新):
$(function(){ //刷新验证码 $("#refreshVerifyCode").click(function(){ refreshVerifyCode();//刷新验证码 }); $("#verifyCode").click(function(){ refreshVerifyCode();//刷新验证码 }); refreshVerifyCode(); });
刷新验证码:
//刷新验证码 functionrefreshVerifyCode(){ $("#verifyCode").attr("src","VerifyCode?t="+newDate().valueOf()); }
判断用户输入的文本是否与验证码相同的Action:
publicActionResultCheckVCode(stringvcode) { if(HttpContext.Session["VerifyCode"].ToString().ToLower()==vcode.ToLower()) { Dictionary<string,object>dic=newDictionary<string,object>(); dic["ok"]=true; returnContent(JsonConvert.SerializeObject(dic)); } else { Dictionary<string,object>dic=newDictionary<string,object>(); dic["ok"]=false; returnContent(JsonConvert.SerializeObject(dic)); } }
以上就是本文的全部内容,希望对大家学习C#生成验证码的方法有所帮助。