ValidateCode.cs 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. using System.Security.Cryptography;
  2. using System.Text;
  3. using Masuit.Tools.Systems;
  4. using SixLabors.Fonts;
  5. using SixLabors.ImageSharp;
  6. using SixLabors.ImageSharp.PixelFormats;
  7. using SixLabors.ImageSharp.Processing;
  8. using SixLabors.ImageSharp.Drawing.Processing;
  9. using SixLabors.ImageSharp.Formats.Webp;
  10. using Path = SixLabors.ImageSharp.Drawing.Path;
  11. namespace Masuit.Tools.Strings;
  12. /// <summary>
  13. /// 画验证码
  14. /// </summary>
  15. public static class ValidateCode
  16. {
  17. /// <summary>
  18. /// 生成验证码
  19. /// </summary>
  20. /// <param name="length">指定验证码的长度</param>
  21. /// <returns>验证码字符串</returns>
  22. public static string CreateValidateCode(int length)
  23. {
  24. string ch = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ1234567890@#$%&?";
  25. byte[] b = new byte[4];
  26. using var cpt = RandomNumberGenerator.Create();
  27. cpt.GetBytes(b);
  28. var r = new Random(BitConverter.ToInt32(b, 0));
  29. var sb = new StringBuilder();
  30. for (int i = 0; i < length; i++)
  31. {
  32. sb.Append(ch[r.StrictNext(ch.Length)]);
  33. }
  34. return sb.ToString();
  35. }
  36. /// <summary>
  37. /// 创建验证码的图片
  38. /// </summary>
  39. /// <param name="validateCode">验证码序列</param>
  40. /// <param name="fontSize">字体大小,默认值28px</param>
  41. /// <exception cref="Exception">The operation failed.</exception>
  42. public static PooledMemoryStream CreateValidateGraphic(this string validateCode, int fontSize = 28)
  43. {
  44. var fontFamily = SystemFonts.Families.Where(f => new[] { "Consolas", "DejaVu Sans", "KaiTi", "NSimSun", "SimSun", "SimHei", "Microsoft YaHei UI", "Arial" }.Contains(f.Name)).OrderByRandom().FirstOrDefault();
  45. if (fontFamily == default)
  46. {
  47. fontFamily = SystemFonts.Families.OrderByRandom().FirstOrDefault();
  48. }
  49. var font = fontFamily.CreateFont(fontSize);
  50. var measure = TextMeasurer.MeasureSize(validateCode, new TextOptions(font));
  51. var width = (int)Math.Ceiling(measure.Width + 15);
  52. var height = (int)Math.Ceiling(measure.Height + 15);
  53. using var image = new Image<Rgba32>(width, height);
  54. //生成随机生成器
  55. Random random = new Random();
  56. //清空图片背景色
  57. image.Mutate(g =>
  58. {
  59. g.BackgroundColor(Color.White);
  60. //画图片的干扰线
  61. for (int i = 0; i < 65; i++)
  62. {
  63. int x1 = random.StrictNext(width);
  64. int x2 = random.StrictNext(width);
  65. int y1 = random.StrictNext(height);
  66. int y2 = random.StrictNext(height);
  67. g.Draw(new SolidPen(new Color(new Rgba32((byte)random.StrictNext(255), (byte)random.StrictNext(255), (byte)random.StrictNext(255))), 1), new Path(new[] { new PointF(x1, y1), new PointF(x2, y2) }));
  68. }
  69. //渐变.
  70. var brush = new LinearGradientBrush(new PointF(0, 0), new PointF(width, height), GradientRepetitionMode.Repeat, new ColorStop(0.5f, Color.Blue), new ColorStop(0.5f, Color.DarkRed));
  71. g.DrawText(validateCode, font, brush, new PointF(3, 2));
  72. //画图片的边框线
  73. g.Draw(Color.Silver, 1, new RectangleF(0, 0, width - 1, height - 1));
  74. });
  75. //画图片的前景干扰点
  76. for (int i = 0; i < 350; i++)
  77. {
  78. int x = random.StrictNext(image.Width);
  79. int y = random.StrictNext(image.Height);
  80. image[x, y] = new Rgba32(random.StrictNext(255), random.StrictNext(255), random.StrictNext(255));
  81. }
  82. //保存图片数据
  83. var stream = new PooledMemoryStream();
  84. image.Save(stream, WebpFormat.Instance);
  85. stream.Position = 0;
  86. return stream;
  87. }
  88. /// <summary>
  89. /// 字符串宽度
  90. /// </summary>
  91. /// <param name="s"></param>
  92. /// <param name="fontSize"></param>
  93. /// <returns></returns>
  94. public static float StringWidth(this string s, int fontSize = 1)
  95. {
  96. var fontFamily = SystemFonts.Families.FirstOrDefault(f => f.Name == "Microsoft YaHei UI");
  97. if (fontFamily == default)
  98. {
  99. fontFamily = SystemFonts.Families.FirstOrDefault();
  100. }
  101. return TextMeasurer.MeasureSize(s, new TextOptions(fontFamily.CreateFont(fontSize))).Width;
  102. }
  103. /// <summary>
  104. /// 字符串宽度
  105. /// </summary>
  106. /// <param name="s"></param>
  107. /// <param name="fontName">字体名字,如:Microsoft YaHei UI</param>
  108. /// <param name="fontSize"></param>
  109. /// <returns></returns>
  110. public static float StringWidth(this string s, string fontName, int fontSize = 1)
  111. {
  112. var fontFamily = SystemFonts.Families.FirstOrDefault(f => f.Name == fontName);
  113. if (fontFamily == default)
  114. {
  115. throw new ArgumentException($"字体 {fontName} 不存在,请尝试其它字体!");
  116. }
  117. return TextMeasurer.MeasureSize(s, new TextOptions(fontFamily.CreateFont(fontSize))).Width;
  118. }
  119. }