ValidateCode.cs 5.6 KB

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