.NET Core 验证码 - LazyCaptcha自定义随机验证码和字体

介绍

LazyCaptcha是仿EasyCaptcha和SimpleCaptcha基于.NET Standard 2.1的图形验证码模块。

LazyCaptcha:https://gitee.com/pojianbing/lazy-captcha

EasyCaptcha:https://gitee.com/ele-admin/EasyCaptcha.

SimpleCaptcha:https://github.com/1992w/SimpleCaptcha

目前Gitee 52star, 如果对您有帮助,请不吝啬点颗星。

一、自定义随机验证码(需要版本1.1.2)

这里随机是指CaptchaType随机,动静随机等等,你可以设置CaptchaOptions任意选项值。每次刷新验证码,效果如下:.NET Core 验证码 - LazyCaptcha自定义随机验证码和字体我也不知道这种需求是否真实存在。

1、自定义RandomCaptcha

/// <summary>
/// 随机验证码
/// </summary>
public class RandomCaptcha : DefaultCaptcha
{
    private static readonly Random random = new();
    private static readonly CaptchaType[] captchaTypes = Enum.GetValues<CaptchaType>();

    public RandomCaptcha(IOptionsSnapshot<CaptchaOptions> options, IStorage storage) : base(options, storage)
    {
    }

    /// <summary>
    /// 更新选项
    /// </summary>
    /// <param name="options"></param>
    protected override void ChangeOptions(CaptchaOptions options)
    {
        // 随机验证码类型
        options.CaptchaType = captchaTypes[random.Next(0, captchaTypes.Length)];

        // 当是算数运算时,CodeLength是指运算数个数
        if (options.CaptchaType.IsArithmetic())
        {
            options.CodeLength = 2;
        }
        else
        {
            options.CodeLength = 4;
        }

        // 如果包含中文时,使用kaiti字体,否则文字乱码
        if (options.CaptchaType.ContainsChinese())
        {
            options.ImageOption.FontFamily = DefaultFontFamilys.Instance.Kaiti;
            options.ImageOption.FontSize = 24;
        }
        else
        {
            options.ImageOption.FontFamily = DefaultFontFamilys.Instance.Actionj;
        }

        // 动静随机
        options.ImageOption.Animation = random.Next(2) == 0;

        // 干扰线随机
        options.ImageOption.InterferenceLineCount = random.Next(1, 4);

        // 气泡随机
        options.ImageOption.BubbleCount = random.Next(1, 4);

        // 其他选项...
    }
}

2、注入RandomCaptcha

// 内存存储, 基于appsettings.json配置
builder.Services.AddCaptcha(builder.Configuration);
// 开启随机验证码
builder.Services.Add(ServiceDescriptor.Scoped<ICaptcha, RandomCaptcha>());

二、自定义字体

使用KG HAPPY字体,效果如图:.NET Core 验证码 - LazyCaptcha自定义随机验证码和字体1、寻找字体

你可以通过fontspace找到自己喜爱的字体。

2、将字体放入项目,并设置为嵌入资源。

当然也可以不作为嵌入资源,放到特定目录也是可以的,只要对下边ResourceFontFamilysFinder稍作修改即可。

.NET Core 验证码 - LazyCaptcha自定义随机验证码和字体
3、定义查找字体帮助类,示例使用ResourceFontFamilysFinder
public class ResourceFontFamilysFinder
{
    private static Lazy<List<FontFamily>> _fontFamilies = new Lazy<List<FontFamily>>(() =>
    {
        var fontFamilies = new List<FontFamily>();
        var assembly = Assembly.GetExecutingAssembly();
        var names = assembly.GetManifestResourceNames();

        if (names?.Length > 0 == true)
        {
            var fontCollection = new FontCollection();
            foreach (var name in names)
            {
                if (!name.EndsWith("ttf")) continue;
                fontFamilies.Add(fontCollection.Add(assembly.GetManifestResourceStream(name)));
            }
        }

        return fontFamilies;
    });
    public static FontFamily Find(string name)
    {
        return _fontFamilies.Value.First(e => e.Name == name);
    }
}

4、设置option

// 内存存储, 基于appsettings.json配置
builder.Services.AddCaptcha(builder.Configuration, options =>
{
    // 自定义字体
    options.ImageOption.FontSize = 28;
    options.ImageOption.FontFamily = ResourceFontFamilysFinder.Find("KG HAPPY"); // 字体的名字在打开ttf文件时会显示
});