前言
图片验证码在我们日常开发中是必不可少会遇见的一个功能,最近工作中就遇到了这个需求,所以下面将实现的方法分享给大家,话不多说了,来一起看看详细的介绍吧。
.NET Core 2.0生成图片验证码
NuGet包引入:ZKWeb.System.Drawing,如下所示:
代码实例如下:VerifyCodeHelper
using System; using System.DrawingCore; using System.DrawingCore.Drawing2D; using System.DrawingCore.Imaging; using System.IO; namespace Common.Helper { public sealed class VerifyCodeHelper { #region 单例模式 //创建私有化静态obj锁 private static readonly object _ObjLock = new object(); //创建私有静态字段,接收类的实例化对象 private static VerifyCodeHelper _VerifyCodeHelper = null; //构造函数私有化 private VerifyCodeHelper() { } //创建单利对象资源并返回 public static VerifyCodeHelper GetSingleObj() { if (_VerifyCodeHelper == null) { lock (_ObjLock) { if (_VerifyCodeHelper == null) _VerifyCodeHelper = new VerifyCodeHelper(); } } return _VerifyCodeHelper; } #endregion #region 生产验证码 public enum VerifyCodeType { NumberVerifyCode, AbcVerifyCode, MixVerifyCode }; /// <summary> /// 1.数字验证码 /// </summary> /// <param name="length"></param> /// <returns></returns> private string CreateNumberVerifyCode(int length) { int[] randMembers = new int[length]; int[] validateNums = new int[length]; string validateNumberStr = ""; //生成起始序列值 int seekSeek = unchecked((int)DateTime.Now.Ticks); Random seekRand = new Random(seekSeek); int beginSeek = seekRand.Next(0, Int32.MaxValue - length * 10000); int[] seeks = new int[length]; for (int i = 0; i < length; i++) { beginSeek += 10000; seeks[i] = beginSeek; } //生成随机数字 for (int i = 0; i < length; i++) { Random rand = new Random(seeks[i]); int pownum = 1 * (int)Math.Pow(10, length); randMembers[i] = rand.Next(pownum, Int32.MaxValue); } //抽取随机数字 for (int i = 0; i < length; i++) { string numStr = randMembers[i].ToString(); int numLength = numStr.Length; Random rand = new Random(); int numPosition = rand.Next(0, numLength - 1); validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1)); } //生成验证码 for (int i = 0; i < length; i++) { validateNumberStr += validateNums[i].ToString(); } return validateNumberStr; } /// <summary> /// 2.字母验证码 /// </summary> /// <param name="length">字符长度</param> /// <returns>验证码字符</returns> private string CreateAbcVerifyCode(int length) { char[] verification = new char[length]; char[] dictionary = { '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' }; Random random = new Random(); for (int i = 0; i < length; i++) { verification[i] = dictionary[random.Next(dictionary.Length - 1)]; } return new string(verification); } /// <summary> /// 3.混合验证码 /// </summary> /// <param name="length">字符长度</param> /// <returns>验证码字符</returns> private string CreateMixVerifyCode(int length) { char[] verification = new char[length]; char[] dictionary = { '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', '0', '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' }; Random random = new Random(); for (int i = 0; i < length; i++) { verification[i] = dictionary[random.Next(dictionary.Length - 1)]; } return new string(verification); } /// <summary> /// 产生验证码(随机产生4-6位) /// </summary> /// <param name="type">验证码类型:数字,字符,符合</param> /// <returns></returns> public string CreateVerifyCode(VerifyCodeType type) { string verifyCode = string.Empty; Random random = new Random(); int length = random.Next(4, 6); switch (type) { case VerifyCodeType.NumberVerifyCode: verifyCode = GetSingleObj().CreateNumberVerifyCode(length); break; case VerifyCodeType.AbcVerifyCode: verifyCode = GetSingleObj().CreateAbcVerifyCode(length); break; case VerifyCodeType.MixVerifyCode: verifyCode = GetSingleObj().CreateMixVerifyCode(length); break; } return verifyCode; } #endregion #region 验证码图片 /// <summary> /// 验证码图片 => Bitmap /// </summary> /// <param name="verifyCode">验证码</param> /// <param name="width">宽</param> /// <param name="height">高</param> /// <returns>Bitmap</returns> public Bitmap CreateBitmapByImgVerifyCode(string verifyCode, int width, int height) { Font font = new Font("Arial", 14, (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(0, (height - totalSizeF.Height) / 2); 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 += curCharSizeF.Width; } //画图片的干扰线 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(); return bitmap; } /// <summary> /// 验证码图片 => byte[] /// </summary> /// <param name="verifyCode">验证码</param> /// <param name="width">宽</param> /// <param name="height">高</param> /// <returns>byte[]</returns> public byte[] CreateByteByImgVerifyCode(string verifyCode, int width, int height) { Font font = new Font("Arial", 14, (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(0, (height - totalSizeF.Height) / 2); 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 += curCharSizeF.Width; } //画图片的干扰线 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(); } #endregion } }
新建控制器:VerifyCodeController,
using System.DrawingCore.Imaging; using System.IO; using Common.Helper; using Microsoft.AspNetCore.Mvc; namespace WebApplicationApi.Controllers { public class VerifyCodeController : Controller { public IActionResult Index() { return View(); } /// <summary> /// 数字验证码 /// </summary> /// <returns></returns> public FileContentResult NumberVerifyCode() { string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode); byte[] codeImage = VerifyCodeHelper.GetSingleObj().CreateByteByImgVerifyCode(code, 100, 40); return File(codeImage, @"image/jpeg"); } /// <summary> /// 字母验证码 /// </summary> /// <returns></returns> public FileContentResult AbcVerifyCode() { string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.AbcVerifyCode); var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40); MemoryStream stream = new MemoryStream(); bitmap.Save(stream, ImageFormat.Png); return File(stream.ToArray(), "image/png"); } /// <summary> /// 混合验证码 /// </summary> /// <returns></returns> public FileContentResult MixVerifyCode() { string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.MixVerifyCode); var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40); MemoryStream stream = new MemoryStream(); bitmap.Save(stream, ImageFormat.Gif); return File(stream.ToArray(), "image/gif"); } } }
添加页面index.cshtml,如下代码:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <figure> <h3>图片验证码</h3> <fieldset> <legend>数字验证码</legend> <img id="nubImg" title="数字验证码" src="/UploadFiles/2021-04-02/NumberVerifyCode">生成验证码如下所示:
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新日志
- 羽泉《给未来的你&天黑天亮》[WAV+CUE][968M]
- 庄心妍《我也许在等候》[低速原抓WAV+CUE]
- 王雅洁《小调歌后2》[原抓WAV+CUE]
- 中国武警男声合唱团《辉煌之声1天路》[DTS-WAV分轨]
- 紫薇《旧曲新韵》[320K/MP3][175.29MB]
- 紫薇《旧曲新韵》[FLAC/分轨][550.18MB]
- 周深《反深代词》[先听版][320K/MP3][72.71MB]
- 李佳薇.2024-会发光的【黑籁音乐】【FLAC分轨】
- 后弦.2012-很有爱【天浩盛世】【WAV+CUE】
- 林俊吉.2012-将你惜命命【美华】【WAV+CUE】
- 晓雅《分享》DTS-WAV
- 黑鸭子2008-飞歌[首版][WAV+CUE]
- 黄乙玲1989-水泼落地难收回[日本天龙版][WAV+CUE]
- 周深《反深代词》[先听版][FLAC/分轨][310.97MB]
- 姜育恒1984《什么时候·串起又散落》台湾复刻版[WAV+CUE][1G]