.NetCore使用SixLabors.ImageSharp跨平台生成验证码

using SixLabors.ImageSharp;
using SixLabors.Fonts;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Drawing.Processing;
using System;
using System.Linq;
using System.Reflection;
namespace Common
{
    /// <summary>
    /// 
    /// </summary>
    public class VerifyCodeHelper
    {
        private static readonly Color[] Colors = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown,
                                                  Color.Brown,Color.DarkBlue};

        //private static readonly int Width = 90;
        //private static readonly int Height = 35;
        private static string GenCode(int length)
        {
            Random _random = new();
            const string chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
            return new string(Enumerable.Repeat(chars, length)
                .Select(s => s[_random.Next(s.Length)]).ToArray());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Width"></param>
        /// <param name="Height"></param>
        /// <param name="FontSize"></param>
        /// <returns></returns>
        public static (string code, byte[] bytes) CreateValidateGraphic(int Width = 80, int Height = 40, int FontSize = 14)
        {
            var code = GenCode(4);
            var r = new Random();
            using var image = new Image<Rgba32>(Width, Height);
            // 字体
            var font = GetFont(FontSize);

            image.Mutate(ctx =>
            {
                // 白底背景
                ctx.Fill(Color.White);

                // 画验证码
                for (int i = 0; i < code.Length; i++)
                {
                    ctx.DrawText(code[i].ToString()
                                 , font
                                 , Colors[r.Next(Colors.Length)]
                                 , new PointF(20 * i + 10, r.Next(2, 12)));
                }
            });
            using var ms = new System.IO.MemoryStream();

            //  格式 自定义
            image.SaveAsPng(ms);
            return (code, ms.ToArray());
        }
        private static Font GetFont(int fontSize)
        {
            const FontStyle fontStyle = FontStyle.Bold;

            // 1. 尝试加载内嵌字体
            try
            {
                var assembly = Assembly.GetExecutingAssembly();

                // 优先尝试 OpenSans,然后 NotoSans
                var fontNames = new[] { "OpenSans-Bold.ttf", "NotoSans-Bold.ttf" };

                foreach (var fontName in fontNames)
                {
                    var resourceName = assembly.GetManifestResourceNames()
                        .FirstOrDefault(n => n.EndsWith(fontName));

                    if (resourceName != null)
                    {
                        using var stream = assembly.GetManifestResourceStream(resourceName);
                        if (stream == null) continue;

                        var fontCollection = new FontCollection();
                        var fontFamily = fontCollection.Add(stream);
                        return fontFamily.CreateFont(fontSize, fontStyle);
                    }
                }
            }
            catch
            {
                // 内嵌字体加载失败,继续尝试系统字体
            }

            // 2. 尝试常见跨平台系统字体
            var systemFonts = new[]
            {
            "DejaVu Sans", "Liberation Sans", "Ubuntu",
            "Roboto", "FreeSans", "Droid Sans", "Arial"
            };

            foreach (var fontName in systemFonts)
            {
                if (SystemFonts.TryGet(fontName, out var fontFamily))
                {
                    return fontFamily.CreateFont(fontSize, fontStyle);
                }
            }

            // 3. 使用第一个可用字体(最终回退)
            return SystemFonts.Families.First().CreateFont(fontSize, fontStyle);
        }

    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值