c# core 生成随机图文验证码
时间:2021-07-29
本文章向大家介绍c# core 生成随机图文验证码,主要包括c# core 生成随机图文验证码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
//随机生成常用的汉字
public string GenerateChineseWords() { int count = 100; string chineseWords = ""; Random rm = new Random(); Encoding gb = Encoding.GetEncoding("gb2312"); for (int i = 0; i < count; i++) { // 获取区码(常用汉字的区码范围为16-55) int regionCode = rm.Next(16, 56); // 获取位码(位码范围为1-94 由于55区的90,91,92,93,94为空,故将其排除) int positionCode; if (regionCode == 55) { // 55区排除90,91,92,93,94 positionCode = rm.Next(1, 90); } else { positionCode = rm.Next(1, 95); } // 转换区位码为机内码 int regionCode_Machine = regionCode + 160;// 160即为十六进制的20H+80H=A0H int positionCode_Machine = positionCode + 160;// 160即为十六进制的20H+80H=A0H // 转换为汉字 byte[] bytes = new byte[] { (byte)regionCode_Machine, (byte)positionCode_Machine }; chineseWords += gb.GetString(bytes); } return chineseWords; }
/// <summary> /// 随机获取汉字 /// </summary> /// <param name="number"></param> /// <returns></returns> private static string RandomHanZi(int number) { //获取常用中文 ChineseCreator chineseCreator = new ChineseCreator(); var str = chineseCreator.GenerateChineseWords(); char[] str_char_arrary = str.ToArray(); Random rand = new Random(); HashSet<string> hs = new HashSet<string>(); bool randomBool = true; while (randomBool) { if (hs.Count == number) break; int rand_number = rand.Next(str_char_arrary.Length); hs.Add(str_char_arrary[rand_number].ToString()); } string code = string.Join("", hs); return code; }
/// <summary> /// 生成图文验证码 /// </summary> /// <param name="numbers">生成位数(默认5位)</param> /// <param name="_height">图片高度</param> /// <param name="_width">图片宽度</param> public object CreateHanZi(int numbers = 5, int _height = 200, int _width = 200) {
//要选择的位数
int choicenumber = 4; var imageModel = new VerificationCodeModel(); try { string code = RandomHanZi(numbers); Bitmap Img = null; Graphics g = null; MemoryStream ms = null; Random random = new Random(); Color[] color_Array = { Color.Black, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple,Color.HotPink ,Color.Fuchsia ,Color.GreenYellow ,Color.Aquamarine }; string[] fonts = { "lnk Free", "Segoe Print", "Comic Sans MS", "MV Boli", "华文行楷" ,"微软雅黑","楷书"}; string _base = Environment.CurrentDirectory + "\\wwwroot\\CodImage\\"; var _file_List = System.IO.Directory.GetFiles(_base); int imageCount = _file_List.Length; if (imageCount == 0) throw new Exception("image not Null"); int imageRandom = random.Next(1, (imageCount + 1)); string _random_file_image = _file_List[imageRandom - 1]; var imageStream = Image.FromFile(_random_file_image); Img = new Bitmap(imageStream, _width, _height); imageStream.Dispose(); g = Graphics.FromImage(Img); Color[] penColor = { Color.LightGray, Color.Green, Color.Blue }; int code_length = code.Length; for (int i = 0; i < code_length; i++) { int cindex = random.Next(color_Array.Length); int findex = random.Next(fonts.Length); Font f = new Font(fonts[findex], 15, FontStyle.Bold); Brush b = new SolidBrush(color_Array[cindex]); int _y = random.Next(_height); if (_y > (_height - 30)) _y = _y - 60; int _x = _width / (i + 1); if ((_width - _x) < 50) { _x = _width - 60; } string word = code.Substring(i, 1); if (imageModel.point_X_Y.Count < choicenumber) { imageModel.point_X_Y.Add(new Point_X_Y() { Word = word, _X = _x, _Y = _y, Sort = i, }); } g.DrawString(word, f, b, _x, _y); } ms = new MemoryStream(); Img.Save(ms, ImageFormat.Jpeg); g.Dispose(); Img.Dispose(); ms.Dispose(); //生成验证码唯一id imageModel.CodeId = Guid.NewGuid().ToString("N"); imageModel.ImageBase64Str = "data:image/jpg;base64," + Convert.ToBase64String(ms.GetBuffer()); } catch (Exception e) { return Task.FromResult(new { result = "出错了", CodeId = "出错了", msg = "出错了" }); } string msg = "请根据顺序点击【" + string.Join("", imageModel.point_X_Y.Select(m => m.Word).ToList()) + "】"; //这是存到了redis 也可以存别的地 TimeSpan second = TimeSpan.FromSeconds(ExpirationSecond); //_redis.StringSetAsync(RedisKeys.VerificationCode+":"+ imageModel.CodeId, imageModel.point_X_Y); _redis.StringSetAsync(RedisKeys.VerificationCode + ":" + imageModel.CodeId, imageModel.point_X_Y, second); return new { result = imageModel.ImageBase64Str, CodeId = imageModel.CodeId, msg = msg }; }
//验证验证码是否正确 public async Task<LoginRes> VerificationCodeAsync(string codeId,List<Point_X_Y> point) { List<Point_X_Y> getRedisCode; var resOk = new LoginRes { code =20000, msg = "验证成功" }; var resErro = new LoginRes { code = 50000, msg = "验证失败" }; try { //验证失败 if (point.Count != choicenumber) return resErro; getRedisCode = await _redis.StringGetAsync<List<Point_X_Y>>(RedisKeys.VerificationCode + ":" + codeId); //验证失败 if (getRedisCode.Count() == 0) return resErro; //验证选择 for (int i = 0; i < getRedisCode.Count(); i++) { var vefA = getRedisCode.Where(m => m.Sort == i).ToList(); var vefB = point.Where(m => m.Sort == i).ToList(); int _x = vefA.FirstOrDefault()._X - vefB.FirstOrDefault()._X; int _y = vefA.FirstOrDefault()._Y - vefB.FirstOrDefault()._Y; string _w = vefA.FirstOrDefault().Word; string _m = vefA.FirstOrDefault().Word; _x = Math.Abs(_x); _y = Math.Abs(_y); if (_x > 25 || _y > 25 || _w != _m) { return resErro; } } //将验证码从redis移除 _redis.Remove(RedisKeys.VerificationCode + ":" + codeId); return resOk; } catch (Exception) { _redis.Remove(RedisKeys.VerificationCode + ":" + codeId); return resErro; }
生成如下图的验证码
原文地址:https://www.cnblogs.com/provedl/p/15076126.html
- Robot Framework | 02 从抛弃RIDE开始创建你的RFS测试
- ASP.NET5 Beta8可用性
- Docker Swarm集群初探
- 数据库逻辑设计
- 06.移动先行之谁主沉浮----我的代码我来写(Xaml的优势)
- [快学Python3]迭代器和生成器
- [快学Python3]INI文件读写
- Vijos P1131 最小公倍数和最大公约数问题【暴力】
- Vjios P1736 铺地毯【暴力,思维】
- Vijos P1116 一元三次方程求解【多解,暴力,二分】
- Python Selenium设计模式-POM
- [快学Python3]HTTP处理 - urllib模块
- Vijos P1786 质因数分解【暴力】
- 模仿百度新闻列表底部的“加载更多”
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Jmeter 常用函数(19)- 详解 __BeanShell
- PyTorch 60分钟入门系列之训练分类器
- Jmeter 常用函数(20)- 详解 __counter
- Jmeter 常用函数(21)- 详解 __char
- Jmeter 常用函数(22)- 详解 __intSum
- Jmeter 常用函数(23)- 详解 __longSum
- Jmeter 常用函数(24)- 详解 __digest
- you-dont-know-websocket
- Cent os 7之KVM虚拟化基础管理
- 常用 Maven 命令介绍
- Linux下diff命令用法详解
- 详解Numpy中的数组拼接、合并操作
- 批量更改图像尺寸到统一大小
- 张东升,我知道是你!如何使用GAN做一个秃头生产器
- Roslyn 在 NuGet 包中放注释 xml 文件的方法