1
0

VerifyCodeHelper.cs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using Admin.Core.Common.Attributes;
  2. using Admin.Core.Common.Configs;
  3. using System;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. using System.IO;
  7. using System.Text;
  8. namespace Admin.Core.Common.Helpers
  9. {
  10. [SingleInstance]
  11. public class VerifyCodeHelper
  12. {
  13. private readonly AppConfig _appConfig;
  14. public VerifyCodeHelper(AppConfig appConfig)
  15. {
  16. _appConfig = appConfig;
  17. }
  18. private string GenerateRandom(int length)
  19. {
  20. var chars = new StringBuilder();
  21. //验证码的字符集,去掉了一些容易混淆的字符
  22. char[] character = { '2', '3', '4', '5', '6', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
  23. Random rnd = new Random();
  24. //生成验证码字符串
  25. for (int i = 0; i < length; i++)
  26. {
  27. chars.Append(character[rnd.Next(character.Length)]);
  28. }
  29. return chars.ToString();
  30. }
  31. public byte[] Draw(out string code, int length = 4)
  32. {
  33. int codeW = 110;
  34. int codeH = 36;
  35. int fontSize = 22;
  36. //颜色列表,用于验证码、噪线、噪点
  37. Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
  38. //字体列表,用于验证码
  39. string[] fonts = _appConfig.VarifyCode.Fonts;
  40. code = GenerateRandom(length);
  41. //创建画布
  42. using (Bitmap bmp = new Bitmap(codeW, codeH))
  43. using (Graphics g = Graphics.FromImage(bmp))
  44. using (MemoryStream ms = new MemoryStream())
  45. {
  46. g.Clear(Color.White);
  47. Random rnd = new Random();
  48. //画噪线
  49. for (int i = 0; i < 1; i++)
  50. {
  51. int x1 = rnd.Next(codeW);
  52. int y1 = rnd.Next(codeH);
  53. int x2 = rnd.Next(codeW);
  54. int y2 = rnd.Next(codeH);
  55. Color clr = color[rnd.Next(color.Length)];
  56. g.DrawLine(new Pen(clr), x1, y1, x2, y2);
  57. }
  58. //画验证码字符串
  59. {
  60. string fnt;
  61. Font ft;
  62. Color clr;
  63. for (int i = 0; i < code.Length; i++)
  64. {
  65. fnt = fonts[rnd.Next(fonts.Length)];
  66. ft = new Font(fnt, fontSize);
  67. clr = color[rnd.Next(color.Length)];
  68. g.DrawString(code[i].ToString(), ft, new SolidBrush(clr), (float)i * 24 + 2, (float)0);
  69. }
  70. }
  71. //将验证码图片写入内存流,并将其以 "image/Png" 格式输出
  72. bmp.Save(ms, ImageFormat.Png);
  73. return ms.ToArray();
  74. }
  75. }
  76. public string GetBase64String(out string code, int length = 4)
  77. {
  78. return Convert.ToBase64String(Draw(out code, length));
  79. }
  80. }
  81. }