1.验证码生成类
1 using System; 2 using System.Collections.Generic; 3 using System.Drawing; 4 using System.Drawing.Drawing2D; 5 using System.Drawing.Imaging; 6 using System.IO; 7 using System.Linq; 8 using System.Web; 9 using System.Web.UI.WebControls; 10 11 namespace AuthenticationDemo.Common 12 { 13 public class ValidationCodeHelper 14 { 15 /// <summary> 16 /// 创建验证码 17 /// </summary> 18 /// <param name="codeLength">验证码位数</param> 19 /// <returns></returns> 20 public string CreateCode(int codeLength) 21 { 22 // 不要 "0" 23 string so = "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,v,w,x,y,z,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"; 24 string[] strArr = so.Split(','); 25 string code = ""; 26 Random rand = new Random(); 27 for (int i = 0; i < codeLength; i++) 28 { 29 code += strArr[rand.Next(0, strArr.Length)]; 30 } 31 return code; 32 } 33 /// <summary> 34 /// 产生图片 35 /// </summary> 36 /// <param name="code">验证码</param> 37 public byte[] CreateImage(string code) 38 { 39 Bitmap image = new Bitmap(64, 32); 40 Graphics g = Graphics.FromImage(image); 41 try 42 { 43 //随机转动角度 44 //int randAngle = 45; 45 //实例随机生成器 46 Random random = new Random(); 47 //清空图片背景色 48 g.Clear(Color.White); 49 //画图片的干扰线 50 for (int i = 0; i < 25; i++) 51 { 52 int x1 = random.Next(image.Width); 53 int x2 = random.Next(image.Width); 54 int y1 = random.Next(image.Height); 55 int y2 = random.Next(image.Height); 56 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 57 } 58 Font font = new Font("Arial", 16, (FontStyle.Bold | FontStyle.Italic)); 59 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), 60 Color.Blue, Color.DarkRed, 1.2f, true); 61 //float angle = random.Next(-randAngle,randAngle); 62 //g.RotateTransform(angle); 63 g.DrawString(code, font, brush, 3, 2); 64 //g.RotateTransform(angle); 65 //画图片的前景干扰点 66 for (int i = 0; i < 100; i++) 67 { 68 int x = random.Next(image.Width); 69 int y = random.Next(image.Height); 70 image.SetPixel(x, y, Color.FromArgb(random.Next())); 71 } 72 //画图片的边框线 73 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 74 //保存图片数据 75 MemoryStream ms = new MemoryStream(); 76 image.Save(ms, ImageFormat.Jpeg); 77 //输出图片流 78 return ms.ToArray(); 79 } 80 catch (Exception) 81 { 82 throw; 83 } 84 finally 85 { 86 g.Dispose(); 87 image.Dispose(); 88 } 89 } 90 91 } 92 }
2.后台调用
public ActionResult GetVCode() { ValidationCodeHelper vc = new ValidationCodeHelper(); //验证码 string code = vc.CreateCode(4); Session["vCode"] = code;//保存生成的验证码,提供之后与用户的输入的验证码比较 byte[] bytes = vc.CreateImage(code); return File(bytes, @"image/jpeg"); }
3.html页面
html代码:
<img id="vCodeImage" src="@Url.Action("GetVCode","Account")?t=@DateTime.Now.Ticks" alt="验证码图片" title="验证码图片" style="display:inline" /> <a href="#" onclick="changeOne()">换一张</a>
js代码:
function changeOne() {
var image = document.getElementById('vCodeImage');
image.src = "@Url.Action("GetVCode","Account")/?t=" + (new Date()).getTime();
}