LazyCaptchaSetup.cs 2.6 KB

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