偶的小收获(关于验证码随机产生图片)

今日偶看mvc设计模式,看见产生一个验证码的生成原理,觉得不错,记下来,空以后有用。
1:前期产生随机的目标字符代码
Create random Code
 1         private string CreateRandomCode(int codeCount)
2 {
3 string allChar = "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,Q,R,S,T,U,W,X,Y,Z";
4 string[] allCharArray = allChar.Split(',');
5 string randomCode = "";
6 int temp = -1;
7
8 Random rand = new Random();
9 for (int i = 0; i < codeCount; i++)
10 {
11 if (temp != -1)
12 {
13 rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
14 }
15 int t = rand.Next(35);
16 if (temp == t)
17 {
18 return CreateRandomCode(codeCount);
19 }
20 temp = t;
21 randomCode += allCharArray[t];
22 }
23 return randomCode;
24 }
2:用随机的字符,进行图片的固化
Create Img Code
 1         /// <summary>
2 /// 创建验证码的图片
3 /// </summary>
4 /// <param name="containsPage">要输出到的page对象</param>
5 /// <param name="validateNum">验证码</param>
6 public byte[] CreateValidateGraphic(string validateCode)
7 {
8 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 23.0), 40);
9 Graphics g = Graphics.FromImage(image);
10 try
11 {
12 //生成随机生成器
13 Random random = new Random();
14 //清空图片背景色
15 g.Clear(Color.White);
16 //画图片的干扰线
17 for (int i = 0; i < 25; i++)
18 {
19 int x1 = random.Next(image.Width);
20 int x2 = random.Next(image.Width);
21 int y1 = random.Next(image.Height);
22 int y2 = random.Next(image.Height);
23 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
24 }
25 Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
26 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
27 Color.Blue, Color.DarkRed, 1.2f, true);
28 g.DrawString(validateCode, font, brush, 22, 10);
29 //画图片的前景干扰点
30 for (int i = 0; i < 80; i++)
31 {
32 int x = random.Next(image.Width);
33 int y = random.Next(image.Height);
34 image.SetPixel(x, y, Color.FromArgb(random.Next()));
35 }
36 //画图片的边框线
37 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
38 //保存图片数据
39 MemoryStream stream = new MemoryStream();
40 image.Save(stream, ImageFormat.Jpeg);
41 //输出图片流
42 return stream.ToArray();
43 }
44 finally
45 {
46 g.Dispose();
47 image.Dispose();
48 }
49 }

  

  

posted @ 2011-08-12 16:19  对象未引用到实例  阅读(209)  评论(0编辑  收藏  举报