RandomCaptcha.cs 2.4 KB

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