LazyCaptchaSetup.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using Lazy.Captcha.Core;
  2. using Lazy.Captcha.Core.Generator;
  3. using Lazy.Captcha.Core.Storage;
  4. namespace Admin.NET.Core;
  5. public static class LazyCaptchaSetup
  6. {
  7. /// <summary>
  8. /// 验证码初始化
  9. /// </summary>
  10. /// <param name="services"></param>
  11. public static void AddLazyCaptcha(this IServiceCollection services)
  12. {
  13. services.AddCaptcha(App.Configuration);
  14. services.AddScoped<ICaptcha, RandomCaptcha>();
  15. }
  16. }
  17. /// <summary>
  18. /// 随机验证码
  19. /// </summary>
  20. public class RandomCaptcha : DefaultCaptcha
  21. {
  22. private static readonly Random random = new();
  23. private static readonly CaptchaType[] captchaTypes = Enum.GetValues<CaptchaType>();
  24. public RandomCaptcha(IOptionsSnapshot<CaptchaOptions> options, IStorage storage) : base(options, storage)
  25. {
  26. }
  27. /// <summary>
  28. /// 更新选项
  29. /// </summary>
  30. /// <param name="options"></param>
  31. protected override void ChangeOptions(CaptchaOptions options)
  32. {
  33. // 随机验证码类型
  34. options.CaptchaType = captchaTypes[random.Next(0, captchaTypes.Length)];
  35. // 当是算数运算时,CodeLength是指运算数个数
  36. if (options.CaptchaType.IsArithmetic())
  37. {
  38. options.CodeLength = 2;
  39. }
  40. else
  41. {
  42. options.CodeLength = 4;
  43. }
  44. // 如果包含中文时,使用kaiti字体,否则文字乱码
  45. if (options.CaptchaType.ContainsChinese())
  46. {
  47. options.ImageOption.FontFamily = DefaultFontFamilys.Instance.Kaiti;
  48. options.ImageOption.FontSize = 24;
  49. }
  50. else
  51. {
  52. options.ImageOption.FontFamily = DefaultFontFamilys.Instance.Actionj;
  53. }
  54. options.IgnoreCase = true; // 忽略大小写
  55. options.ImageOption.Animation = random.Next(2) == 0; // 动静
  56. options.ImageOption.InterferenceLineCount = random.Next(1, 5); // 干扰线数量
  57. options.ImageOption.BubbleCount = random.Next(1, 5); // 气泡数量
  58. //options.ImageOption.BubbleMinRadius = 5; // 气泡最小半径
  59. //options.ImageOption.BubbleMaxRadius = 15; // 气泡最大半径
  60. //options.ImageOption.BubbleThickness = 1; // 气泡边沿厚度
  61. options.ImageOption.BackgroundColor = SixLabors.ImageSharp.Color.White; // 背景色
  62. options.ImageOption.Width = 150; // 验证码宽度
  63. options.ImageOption.Height = 50; // 验证码高度
  64. options.ImageOption.FontSize = 36; // 字体大小
  65. //options.ImageOption.FontFamily = DefaultFontFamilys.Instance.Actionj; // 字体
  66. }
  67. }