控制器的代碼如下
1 public ActionResult SecurityCode() 2 { 3 string oldcode = TempData["SecurityCode"] as string; 4 string code = CreateRandomCode(4); //驗證碼的字符為4個 5 TempData["SecurityCode"] = code; //驗證碼存放在TempData中 6 return File(CreateValidateGraphic(code), "image/Jpeg"); 7 } 8 9 /// <summary> 10 /// 生成隨機的字符串 11 /// </summary> 12 /// <param name="codeCount"></param> 13 /// <returns></returns> 14 public string CreateRandomCode(int codeCount) 15 { 16 string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,a,b,c,d,e,f,g,h,i,g,k,l,m,n,o,p,q,r,F,G,H,I,G,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,s,t,u,v,w,x,y,z"; 17 string[] allCharArray = allChar.Split(','); 18 string randomCode = ""; 19 int temp = -1; 20 Random rand = new Random(); 21 for (int i = 0; i < codeCount; i++) 22 { 23 if (temp != -1) 24 { 25 rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); 26 } 27 int t = rand.Next(35); 28 if (temp == t) 29 { 30 return CreateRandomCode(codeCount); 31 } 32 temp = t; 33 randomCode += allCharArray[t]; 34 } 35 return randomCode; 36 } 37 38 /// <summary> 39 /// 創建驗證碼圖片 40 /// </summary> 41 /// <param name="validateCode"></param> 42 /// <returns></returns> 43 public byte[] CreateValidateGraphic(string validateCode) 44 { 45 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 16.0), 27); 46 Graphics g = Graphics.FromImage(image); 47 try 48 { 49 //生成隨機生成器 50 Random random = new Random(); 51 //清空圖片背景色 52 g.Clear(Color.White); 53 //畫圖片的干擾線 54 for (int i = 0; i < 25; i++) 55 { 56 int x1 = random.Next(image.Width); 57 int x2 = random.Next(image.Width); 58 int y1 = random.Next(image.Height); 59 int y2 = random.Next(image.Height); 60 g.DrawLine(new Pen(Color.Silver), x1, x2, y1, y2); 61 } 62 Font font = new Font("Arial", 13, (FontStyle.Bold | FontStyle.Italic)); 63 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); 64 g.DrawString(validateCode, font, brush, 3, 2); 65 66 //畫圖片的前景干擾線 67 for (int i = 0; i < 100; i++) 68 { 69 int x = random.Next(image.Width); 70 int y = random.Next(image.Height); 71 image.SetPixel(x, y, Color.FromArgb(random.Next())); 72 } 73 //畫圖片的邊框線 74 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 75 76 //保存圖片數據 77 MemoryStream stream = new MemoryStream(); 78 image.Save(stream, ImageFormat.Jpeg); 79 80 //輸出圖片流 81 return stream.ToArray(); 82 } 83 finally 84 { 85 g.Dispose(); 86 image.Dispose(); 87 } 88 }
在視圖中使用:
1 <img src="/Account/SecurityCode" onclick="this.src=this.src+'?'"/>