public class ValidateCode{/// <summary>/// 创建随机数/// </summary>/// <param name="num"></param>/// <returns></returns>public string CreateRandom(int num){string str = "ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";StringBuilder sb = new StringBuilder();for (int i = 0; i < num; i++){sb.Append(str[new Random(Guid.NewGuid().GetHashCode()).Next(0, str.Length - 1)]);}return sb.ToString();}/// <summary>/// 验证码图片 => byte[]/// </summary>/// <param name="verifyCode">验证码</param>/// <param name="width">宽</param>/// <param name="height">高</param>/// <param name="fontsize">字体大小</param>/// <returns></returns>public byte[] CreateByteByImgVerifyCode(string verifyCode, int width, int height, int fontsize){Font font = new Font("Arial", fontsize, (FontStyle.Bold | FontStyle.Italic));Brush brush;Bitmap bitmap = new Bitmap(width, height);Graphics g = Graphics.FromImage(bitmap);SizeF totalSizeF = g.MeasureString(verifyCode, font);SizeF curCharSizeF;PointF startPointF = new PointF(10, (height - totalSizeF.Height) / 2); //x=5开始int wx = ((width - 20) / verifyCode.Length); //间距Random random = new Random(); //随机数产生器g.Clear(Color.White); //清空图片背景色 for (int i = 0; i < verifyCode.Length; i++){brush = new LinearGradientBrush(new Point(0, 0), new Point(1, 1), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255)), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255)));g.DrawString(verifyCode[i].ToString(), font, brush, startPointF);curCharSizeF = g.MeasureString(verifyCode[i].ToString(), font);startPointF.X += wx;}//画图片的干扰线 for (int i = 0; i < 10; i++){int x1 = random.Next(bitmap.Width);int x2 = random.Next(bitmap.Width);int y1 = random.Next(bitmap.Height);int y2 = random.Next(bitmap.Height);g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);}//画图片的前景干扰点 for (int i = 0; i < 100; i++){int x = random.Next(bitmap.Width);int y = random.Next(bitmap.Height);bitmap.SetPixel(x, y, Color.FromArgb(random.Next()));}g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1); //画图片的边框线 g.Dispose();//保存图片数据 MemoryStream stream = new MemoryStream();bitmap.Save(stream, ImageFormat.Jpeg);//输出图片流 return stream.ToArray();}}
然后做一个接口
public ActionResult Captcha(){ValidateCode validateCode = new ValidateCode();string code = validateCode.CreateRandom(4);Session["code"] = code.ToLower();return File(validateCode.CreateByteByImgVerifyCode(code, 130, 48, 22), "image/jpg");}
然后前端调用:
<div style="margin-left: 10px;"><img src="/@ViewContext.RouteData.DataTokens["area"]/login/Captcha" class="layadmin-user-login-codeimg" id="LAY-user-get-vercode"></div>
如果验证码不出来,可能是服务没有打开,需要打开这个服务
如果没有,请安装一下,这个自行找下