![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary>
2 /// 随机生成验证码
3 /// </summary>
4 protected void CreateSecCode()
5 {
6 //创建一个包含随机内容的验证码文本
7 System.Random rand = new Random();
8 int len = rand.Next(4, 6);//返回一个大于等于4,小于6的整型随机数
9 char[] chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();//定义一个char数组
10
11 //用于追加字符串,效率比string更高效
12 System.Text.StringBuilder myStr = new System.Text.StringBuilder();
13
14 for (int iCount = 0; iCount < len; iCount++)
15 {
16 myStr.Append(chars[rand.Next(chars.Length)]);
17 }
18 string text = myStr.ToString();//生成的随机内容
19
20 // 保存验证码到 session 中以便其他模块使用
21 this.Session["checkcode"] = text;
22
23 Size ImageSize = Size.Empty;//用于存储验证码图片大小
24 Font myFont = new Font("MS Sans Serif", 20);
25
26 // 计算验证码图片大小
27 using (Bitmap bmp = new Bitmap(10, 10))
28 {
29 using (Graphics g = Graphics.FromImage(bmp))
30 {
31 SizeF size = g.MeasureString(text, myFont, 10000);//获取特定字体样式的文本大小
32 ImageSize.Width = (int)size.Width + 8;
33 ImageSize.Height = (int)size.Height + 8;
34 }
35 }
36
37 // 创建验证码图片
38 using (Bitmap bmp = new Bitmap(ImageSize.Width, ImageSize.Height))
39 {
40 // 绘制验证码文本
41 using (Graphics g = Graphics.FromImage(bmp))
42 {
43 g.Clear(Color.White);
44 using (StringFormat f = new StringFormat())
45 {
46 f.Alignment = StringAlignment.Near;
47 f.LineAlignment = StringAlignment.Center;
48 f.FormatFlags = StringFormatFlags.NoWrap;
49 g.DrawString(
50 text,
51 myFont,
52 Brushes.Red,
53 new RectangleF(
54 0,
55 0,
56 ImageSize.Width,
57 ImageSize.Height),
58 f);
59 }//using
60 }//using
61
62 // 制造噪声 杂点面积占图片面积的 8%
63 int num = ImageSize.Width * ImageSize.Height * 8 / 100;
64
65 for (int iCount = 0; iCount < num; iCount++)
66 {
67 // 在随机的位置使用随机的颜色设置图片的像素
68 int x = rand.Next(ImageSize.Width);
69 int y = rand.Next(ImageSize.Height);
70 int r = rand.Next(255);
71 int g = rand.Next(255);
72 int b = rand.Next(255);
73 Color c = Color.FromArgb(r, g, b);
74 bmp.SetPixel(x, y, c);
75 }//for
76
77 // 输出图片
78 System.IO.MemoryStream ms = new System.IO.MemoryStream();
79 bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
80 this.Response.ContentType = "image/png";
81 ms.WriteTo(this.Response.OutputStream);
82 ms.Close();
83 }//using
84
85 myFont.Dispose();
86 }