VerifyCodeHelper.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. namespace Admin.Core.Common.Helpers
  7. {
  8. public class VerifyCodeHelper
  9. {
  10. private static string GenerateRandom(int length)
  11. {
  12. var chars = new StringBuilder();
  13. //验证码的字符集,去掉了一些容易混淆的字符
  14. 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' };
  15. Random rnd = new Random();
  16. //生成验证码字符串
  17. for (int i = 0; i < length; i++)
  18. {
  19. chars.Append(character[rnd.Next(character.Length)]);
  20. }
  21. return chars.ToString();
  22. }
  23. public static byte[] Draw(out string code, int length = 4)
  24. {
  25. int codeW = 110;
  26. int codeH = 36;
  27. int fontSize = 22;
  28. //颜色列表,用于验证码、噪线、噪点
  29. Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue };
  30. //字体列表,用于验证码
  31. string[] font = { "Times New Roman", "Verdana", "Arial", "Gungsuh", "Impact" };
  32. code = GenerateRandom(length);
  33. //创建画布
  34. using (Bitmap bmp = new Bitmap(codeW, codeH))
  35. using (Graphics g = Graphics.FromImage(bmp))
  36. using (MemoryStream ms = new MemoryStream())
  37. {
  38. g.Clear(Color.White);
  39. Random rnd = new Random();
  40. //画噪线
  41. for (int i = 0; i < 1; i++)
  42. {
  43. int x1 = rnd.Next(codeW);
  44. int y1 = rnd.Next(codeH);
  45. int x2 = rnd.Next(codeW);
  46. int y2 = rnd.Next(codeH);
  47. Color clr = color[rnd.Next(color.Length)];
  48. g.DrawLine(new Pen(clr), x1, y1, x2, y2);
  49. }
  50. //画验证码字符串
  51. {
  52. string fnt;
  53. Font ft;
  54. Color clr;
  55. for (int i = 0; i < code.Length; i++)
  56. {
  57. fnt = font[rnd.Next(font.Length)];
  58. ft = new Font(fnt, fontSize);
  59. clr = color[rnd.Next(color.Length)];
  60. g.DrawString(code[i].ToString(), ft, new SolidBrush(clr), (float)i * 24 + 2, (float)0);
  61. }
  62. }
  63. //将验证码图片写入内存流,并将其以 "image/Png" 格式输出
  64. bmp.Save(ms, ImageFormat.Png);
  65. return ms.ToArray();
  66. }
  67. }
  68. public static string GetBase64String(out string code, int length = 4)
  69. {
  70. return Convert.ToBase64String(Draw(out code, length));
  71. }
  72. }
  73. }