轉載出處:http://blog.csdn.net/loverszhaokai/archive/2010/10/04/5921139.aspx
/////////////////////////////////////////////////////////////////////////////////////////
//如果想進行登陸的時候驗證。只要判斷用戶輸入的數據是否和Session[“Validate”]相等就行了//
////////////////////////////////////////////////////////////////////////////////////////
01.using System;
02.using System.Drawing;
03.public partial class 生成隨機圖片 : System.Web.UI.Page
04.{
05. //生成隨機圖片背景
06. protected void CreateImageM(string validateCode)
07. {
08. //圖像的寬度,與驗證碼的長度成一定比例
09. int iwidth = (int)(validateCode.Length * 11.5);
10. //創建一個長20,寬iwidth的圖像對象
11. System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth,20);
12. //創建一個新繪圖對象
13. Graphics g = Graphics.FromImage(image);
14. //繪圖用的字體和字號
15. Font f = new System.Drawing.Font("Arial",10,System.Drawing.FontStyle.Bold);
16. //繪圖用的刷子的大小
17. Brush b = new System.Drawing.SolidBrush(Color.White);
18. //清除背景色,並且以深橄欖色填充
19. g.Clear(Color.DarkOliveGreen);
20. //格式化刷子的屬性,用指定的刷子、顏色等在指定的範圍內畫圖
21. g.DrawString(validateCode,f,b,3,3);
22. //創建鉛筆對象
23. Pen blackPen = new Pen(Color.Black,0);
24. //創建隨機對象
25. Random rand = new Random();
26. //隨機畫線
27. for (int i = 0; i < 5; i++)
28. {
29. int y = rand.Next(image.Height);
30. //用指定的鉛筆畫線,粗細由參數決定
31. g.DrawLine(blackPen,0,y,image.Width,y);
32. }
33. //輸出繪圖
34. System.IO.MemoryStream ms = new System.IO.MemoryStream();
35. //將圖像保存到指定的流
36. image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
37. Response.ClearContent();
38. //配置輸出類型
39. Response.ContentType = "Image/Jpeg";
40. //輸入內容
41. Response.BinaryWrite(ms.ToArray());
42. //清空不需要的資源
43. g.Dispose();
44. image.Dispose();
45. }
46. //生成隨機字符的方法
47. protected string CreateValidate(int count)
48. {
49. 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";
50. //將驗證碼中所有的字符保存在一個字符串數組中
51. string[] allchararray = allchar.Split(',');
52. //初始化一個隨機數
53. string randomcode = "";
54. int temp = -1;
55. //生成一個隨機對象
56. Random rand = new Random();
57. //根據驗證碼的位數循環
58. for (int i = 0; i < count; i++)
59. {
60. //主要是防止生成相同的驗證碼
61. if (temp != -1)
62. {
63. //加入時間的刻度
64. rand = new Random(i*temp*((int)DateTime.Now.Ticks));
65. }
66. int t = rand.Next(35);
67. if (temp == t)
68. {
69. //相等的話重新生成
70. return CreateValidate(count);
71. }
72. temp = t;
73. randomcode += allchararray[t];
74. }
75. //在session中保存隨機驗證碼
76. Session["Valid"] = randomcode;
77. //返回生成的隨機字符
78. return randomcode;
79. }
80. protected void Page_Load(object sender, EventArgs e)
81. {
82. CreateImageM(CreateValidate(8));
83. }
84.}