1 protected void Page_Load(object sender, EventArgs e)
2 {
3 string tmp = RndNum(4);
4 HttpCookie a = new HttpCookie("ImageV", tmp);
5 Response.Cookies.Add(a);
6 this.ValidateCode(tmp);
7 }
8 private void ValidateCode(string VNum)
9 {
10 Bitmap Img = null;
11 Graphics g = null;
12 MemoryStream ms = null;
13
14 int gheight = VNum.Length * 12;
15 Img = new Bitmap(gheight, 25);
16 g = Graphics.FromImage(Img);
17 //背景颜色
18 g.Clear(Color.LightSteelBlue);
19 //文字字体
20 Font f = new Font("Arial Black", 10);
21 //文字颜色
22 SolidBrush s = new SolidBrush(Color.RoyalBlue);
23 g.DrawString(VNum, f, s, 3, 3);
24 ms = new MemoryStream();
25 Img.Save(ms, ImageFormat.Jpeg);
26 Response.ClearContent();
27 Response.ContentType = "images/Jpeg";
28 Response.BinaryWrite(ms.ToArray());
29 g.Dispose();
30 Img.Dispose();
31 Response.End();
32 }
33
34 private string RndNum(int VcodeNum)
35 {
36 string Vchar = "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" +
37 ",q,r,s,t,u,v,w,x,y,z";
38 string[] VcArray = Vchar.Split(new Char[] { ',' });
39 string VNum = "";
40 int temp = -1;
41
42 Random rand = new Random();
43
44 for (int i = 1; i < VcodeNum + 1; i++)
45 {
46 if (temp != -1)
47 {
48 rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
49 }
50
51 int t = rand.Next(35);
52 if (temp != -1 && temp == t)
53 {
54 return RndNum(VcodeNum);
55 }
56 temp = t;
57 VNum += VcArray[t];
58 }
59 return VNum;
60 }
2 {
3 string tmp = RndNum(4);
4 HttpCookie a = new HttpCookie("ImageV", tmp);
5 Response.Cookies.Add(a);
6 this.ValidateCode(tmp);
7 }
8 private void ValidateCode(string VNum)
9 {
10 Bitmap Img = null;
11 Graphics g = null;
12 MemoryStream ms = null;
13
14 int gheight = VNum.Length * 12;
15 Img = new Bitmap(gheight, 25);
16 g = Graphics.FromImage(Img);
17 //背景颜色
18 g.Clear(Color.LightSteelBlue);
19 //文字字体
20 Font f = new Font("Arial Black", 10);
21 //文字颜色
22 SolidBrush s = new SolidBrush(Color.RoyalBlue);
23 g.DrawString(VNum, f, s, 3, 3);
24 ms = new MemoryStream();
25 Img.Save(ms, ImageFormat.Jpeg);
26 Response.ClearContent();
27 Response.ContentType = "images/Jpeg";
28 Response.BinaryWrite(ms.ToArray());
29 g.Dispose();
30 Img.Dispose();
31 Response.End();
32 }
33
34 private string RndNum(int VcodeNum)
35 {
36 string Vchar = "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" +
37 ",q,r,s,t,u,v,w,x,y,z";
38 string[] VcArray = Vchar.Split(new Char[] { ',' });
39 string VNum = "";
40 int temp = -1;
41
42 Random rand = new Random();
43
44 for (int i = 1; i < VcodeNum + 1; i++)
45 {
46 if (temp != -1)
47 {
48 rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
49 }
50
51 int t = rand.Next(35);
52 if (temp != -1 && temp == t)
53 {
54 return RndNum(VcodeNum);
55 }
56 temp = t;
57 VNum += VcArray[t];
58 }
59 return VNum;
60 }
使用方法:
在需要它的页面html里添加
<img src="identifyingcode.aspx" />
HttpCookieCollection cookies = Request.Cookies;
string tmp = cookies["ImageV"].Value;
然后比tmp与获取的较验证码文本框中的值是否相同