//随机生成常用的汉字
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; }
生成如下图的验证码