ValidateCode.cs 4.5 KB

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