生成登录验证码(asp.net)

第一步:创建一个类CreateImage
1 public class CreateImage
2 {
3internalstaticvoidDrawImage()
4{
5CreateImageimg=newCreateImage();
6HttpContext.Current.Session["CheckCode"]=img.RndNum(4);
7img.CreateImages(HttpContext.Current.Session["CheckCode"].ToString());
8}

9
10/**////<summary>
11///生成验证图片
12///</summary>
13///<paramname="checkCode">验证字符</param>

14privatevoidCreateImages(stringcheckCode)
15{
16intiwidth=(int)(checkCode.Length*13);
17System.Drawing.Bitmapimage=newSystem.Drawing.Bitmap(iwidth,20);
18Graphicsg=Graphics.FromImage(image);
19g.Clear(Color.White);
20//定义颜色
21Color[]c={Color.Black,Color.Red,Color.DarkBlue,Color.Green,Color.Orange,Color.Brown,Color.DarkCyan,Color.Purple};
22//定义字体
23string[]font={"Verdana","MicrosoftSansSerif","ComicSansMS","Arial","宋体"};
24Randomrand=newRandom();
25//随机输出噪点
26for(inti=0;i<50;i++)
27{
28intx=rand.Next(image.Width);
29inty=rand.Next(image.Height);
30g.DrawRectangle(newPen(Color.LightGray,0),x,y,1,1);
31}

32
33//输出不同字体和颜色的验证码字符
34for(inti=0;i<checkCode.Length;i++)
35{
36intcindex=rand.Next(7);
37intfindex=rand.Next(5);
38
39Fontf=newSystem.Drawing.Font(font[findex],10,System.Drawing.FontStyle.Bold);
40Brushb=newSystem.Drawing.SolidBrush(c[cindex]);
41intii=4;
42if((i+1)%2==0)
43{
44ii=2;
45}

46g.DrawString(checkCode.Substring(i,1),f,b,3+(i*12),ii);
47}

48//画一个边框
49g.DrawRectangle(newPen(Color.Black,0),0,0,image.Width-1,image.Height-1);
50
51//输出到浏览器
52System.IO.MemoryStreamms=newSystem.IO.MemoryStream();
53image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
54HttpContext.Current.Response.ClearContent();
55//Response.ClearContent();
56HttpContext.Current.Response.ContentType="image/Jpeg";
57HttpContext.Current.Response.BinaryWrite(ms.ToArray());
58g.Dispose();
59image.Dispose();
60}

61
62/**////<summary>
63///生成随机的字母
64///</summary>
65///<paramname="VcodeNum">生成字母的个数</param>
66///<returns>string</returns>

67privatestringRndNum(intVcodeNum)
68{
69stringVchar="0,1,2,3,4,5,6,7,8,9";
70string[]VcArray=Vchar.Split(',');
71stringVNum="";//由于字符串很短,就不用StringBuilder了
72inttemp=-1;//记录上次随机数值,尽量避免生产几个一样的随机数
73
74//采用一个简单的算法以保证生成随机数的不同
75Randomrand=newRandom();
76for(inti=1;i<VcodeNum+1;i++)
77{
78if(temp!=-1)
79{
80rand=newRandom(i*temp*unchecked((int)DateTime.Now.Ticks));
81}

82intt=rand.Next(VcArray.Length);
83if(temp!=-1&&temp==t)
84{
85returnRndNum(VcodeNum);
86}

87temp=t;
88VNum+=VcArray[t];
89
90}

91returnVNum;
92}

93}
第二步:建立一个页面Image.aspx在Page_Load事件中
CreateImage.DrawImage();
第三步在调用生成验证码的页面写:
1 < scriptlanguage = " JavaScript " >
2 <!--
3 var numkey = Math.random();
4 numkey = Math.round(numkey * 10000 );
5 document.write( " <imgsrc=\ " Image.aspx ? k = " +numkey+ " \ " width=\ " 52 \ " height=\ " 20 \ "" );
6 // -->
7 </ script >
8
第四步验证的方法:
1 if (TbCode.Text.Trim().ToString() != Session[ " CheckCode " ].ToString())
2 {
3Response.Write("<scriptlanguage='javascript'>alert('验证码不正确!');</script>");
4TbCode.Text="";
5TbCode.Focus();
6}

7

你可能感兴趣的:(JavaScript,.net,算法,asp.net,asp)