ValidateCode.cs 5.3 KB

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