随机生成验证码和图片
1.随机生成由数字和字母组成的验证码
1 /// <summary> 2 /// 生成由数字和字母组成的验证码 3 /// </summary> 4 /// <param name="length"></param> 5 /// <returns></returns> 6 public static string CreateValidateCodeWithStr(int length) 7 { 8 string str = @"0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ"; 9 StringBuilder validateNumberStr = new StringBuilder(); 10 Random r = new Random(); 11 for (int i = 0; i < length; i++) 12 { 13 validateNumberStr.Append(str.Substring(0 + r.Next(61), 1)); 14 } 15 return validateNumberStr.ToString(); 16 17
2.由验证码生成对应的图片
1 /// <summary> 2 /// 创建验证码的图片 3 /// </summary> 4 /// <param name="containsPage">要输出到的page对象</param> 5 /// <param name="validateNum">验证码</param> 6 public static byte[] CreateValidateGraphic(string validateCode) 7 { 8 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22); 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, 3, 2); 29 //画图片的前景干扰点 30 for (int i = 0; i < 100; 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 }
3.在控制器中调用
1 public FileContentResult GetValidateCode() 2 { 3 string code = ValidateCode.CreateValidateCodeWithStr(4); 4 5 return File(ValidateCode.CreateValidateGraphic(code),"image/jpeg"); 6 }
4.在视图中调用
1 <script> 2 function RefValidateCode() { 3 var r = Math.random(); 4 $("#img2").attr('src', '../Home/GetValidateCode?ashfjd=' + r + ''); 5 } 6 </script> 7 <div> 8 <div style="padding: 40px;"> 9 <img id="img2" src="@Url.Action("GetValidateCode", "Home")" onclick="RefValidateCode()" /> 10 </div> 11 </div>

浙公网安备 33010602011771号