ValidateCode.cs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 font = SystemFonts.Families.Where(f => new[] { "Consolas", "KaiTi", "NSimSun", "SimSun", "SimHei", "Microsoft YaHei UI", "Arial" }.Contains(f.Name)).OrderByRandom().FirstOrDefault().CreateFont(fontSize);
  54. var measure = TextMeasurer.Measure(validateCode, new TextOptions(font));
  55. var width = (int)Math.Ceiling(measure.Width * 1.5);
  56. var height = (int)Math.Ceiling(measure.Height + 5);
  57. using var image = new Image<Rgba32>(width, height);
  58. //生成随机生成器
  59. Random random = new Random();
  60. //清空图片背景色
  61. image.Mutate(g =>
  62. {
  63. g.BackgroundColor(Color.White);
  64. //画图片的干扰线
  65. for (int i = 0; i < 75; i++)
  66. {
  67. int x1 = random.StrictNext(width);
  68. int x2 = random.StrictNext(width);
  69. int y1 = random.StrictNext(height);
  70. int y2 = random.StrictNext(height);
  71. 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));
  72. }
  73. //渐变.
  74. 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));
  75. g.DrawText(validateCode, font, brush, new PointF(3, 2));
  76. //画图片的边框线
  77. g.DrawLines(new Pen(Color.Silver, 1), new PointF(0, 0), new PointF(width - 1, height - 1));
  78. });
  79. //画图片的前景干扰点
  80. for (int i = 0; i < 350; i++)
  81. {
  82. int x = random.StrictNext(image.Width);
  83. int y = random.StrictNext(image.Height);
  84. image[x, y] = new Rgba32(random.StrictNext(255), random.StrictNext(255), random.StrictNext(255));
  85. }
  86. //保存图片数据
  87. using MemoryStream stream = new MemoryStream();
  88. image.Save(stream, WebpFormat.Instance);
  89. //输出图片流
  90. context.Response.Clear();
  91. context.Response.ContentType = ContentType.Jpeg;
  92. return stream.ToArray();
  93. }
  94. }
  95. }