c#生成验证码
1 新建一个asp.net页面。。内容如下
2 private void Page_Load(object sender, System.EventArgs e)
3 {
4 this.CreateCheckCodeImage(GenerateCheckCode());
5 }
6
7
8 private string GenerateCheckCode()
9 {
10 int number;
11 char code;
12 string checkCode = String.Empty;//初始为空字符串
13
14 System.Random random = new Random();
15
16 for (int i = 0; i < 5; i++)
17 {
18 number = random.Next();
19
20 if (number % 2 == 0)
21 code = (char)('0' + (char)(number % 10));
22 else
23 code = (char)('A' + (char)(number % 26));
24
25 checkCode += code.ToString();
26 }
27
28
29 HttpContext.Current.Session["CheckCode"] = checkCode;
30
31 return checkCode;
32
33 }
34
35
36private void CreateCheckCodeImage(string checkCode)
37 {
38 if (checkCode == null || checkCode.Trim() == String.Empty)
39 return;
40
41 System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
42 Graphics g = Graphics.FromImage(image);
43
44 try
45 {
46 //生成随机生成器
47 Random random = new Random();
48
49 //清空图片背景色
50 g.Clear(Color.White);
51
52 //画图片的背景噪音线
53 for (int i = 0; i < 25; i++)
54 {
55 int x1 = random.Next(image.Width);
56 int x2 = random.Next(image.Width);
57 int y1 = random.Next(image.Height);
58 int y2 = random.Next(image.Height);
59
60 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
61 }
62
63 Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
64 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);
65 g.DrawString(checkCode, font, brush, 2, 2);
66
67 //画图片的前景噪音点
68 for (int i = 0; i < 100; i++)
69 {
70 int x = random.Next(image.Width);
71 int y = random.Next(image.Height);
72
73 image.SetPixel(x, y, Color.FromArgb(random.Next()));
74 }
75
76 //画图片的边框线
77 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
78
79 System.IO.MemoryStream ms = new System.IO.MemoryStream();
80 image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
81 Response.ClearContent();
82 Response.ContentType = "image/Gif";
83 Response.BinaryWrite(ms.ToArray());
84 }
85 finally
86 {
87 g.Dispose();
88 image.Dispose();
89 }
90
91 }
92}
93需要验证码的页面放一个Image空间。。背景设置为这个页面
94/*
95 后台:
96
97 if (Session["checkcode"] == null)
98 {
99 Response.Write("您输入的验证码不正确,请重新输入!");
100 }
101
102 if (TextBox1.Text.Equals(Session["checkcode"].ToString()))
103 {
104 Response.Redirect("default.aspx");
105 }
106 else
107 {
108 Response.Write("请重新输入验证码!");
109 }
110
111 */