木木代码人生

自在,逍遥

导航

ASP.net中验证码的产生

1 using System;
2 using System.Collections;
3 using System.Configuration;
4 using System.Data;
5 using System.Linq;
6 using System.Web;
7 using System.Web.Security;
8 using System.Web.UI;
9 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;
13 using System.Drawing;
14
15 public partial class tupian : System.Web.UI.Page
16 {
17 protected void Page_Load(object sender, EventArgs e)
18 {
19 if (!IsPostBack)
20 {
21
22 string name = Create();
23 CrateImage(name);
24 Session["names"] = name;
25 }
26 }
27 private string Create()
28 {
29 string allchar = "1,2,3,4,5,6,7,8,9,0,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";
30 string[] allchararray = allchar.Split(',');//拆分字符串
31 string randomNum = "";
32 int temp = -1;
33 Random rand = new Random();
34 for (int i = 0; i < 5; i++)
35 {
36 if (temp != -1)
37 {
38 rand = new Random(i * temp * (int)DateTime.Now.Ticks);
39 }
40 int t = rand.Next(35);
41 if (temp == t)
42 {
43 return Create();
44 }
45 temp = t;
46 randomNum += allchararray[t];
47 }
48 return randomNum;
49 }
50 private void CrateImage(string name)
51 {
52 if (name == null || name.Trim()==string.Empty )
53 {
54 return ;
55 }
56 System.Drawing.Bitmap image = new System.Drawing.Bitmap(name.Length * 12 + 10, 22);
57 Graphics g = Graphics.FromImage(image);
58 try {
59 Random rand = new Random();
60 g.Clear(Color .White );
61 for (int i = 0; i < 25; i++)
62 {
63
64 int x1 = rand.Next(image.Width);
65 int x2 = rand.Next(image.Width);
66 int y1 = rand.Next(image.Height);
67 int y2 = rand.Next(image.Height);
68 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
69 }
70 Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
71 System.Drawing .Drawing2D .LinearGradientBrush brush=new System.Drawing.Drawing2D.LinearGradientBrush (new Rectangle(0,0,image .Width,image.Height ),Color .Blue,Color .DarkRed,1.2f,true);
72 g.DrawString (name,font,brush,2,2);
73 for(int i=0;i<100;i++)
74 {
75 int x=rand .Next (image.Width );
76 int y=rand.Next (image.Height );
77 image.SetPixel (x,y,Color.FromArgb (rand .Next ()));
78
79 }
80 g.DrawRectangle (new Pen(Color.Silver),0,0,image.Width -1,image .Height -1);
81 System.IO.MemoryStream ms=new System.IO.MemoryStream ();
82 image.Save (ms,System.Drawing .Imaging.ImageFormat .Gif);
83 Response .ContentType ="image/Gif";
84 Response .BinaryWrite(ms.ToArray ());
85 }
86 finally{
87 g.Dispose ();
88 image.Dispose();
89 }
90
91 }
92 }
在里一个网页中的imagebutton中的url中调用这个网页的地址,把生成的验证码用session来传递;

posted on 2011-03-06 10:10  木木代码人生  阅读(224)  评论(0编辑  收藏  举报