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);
}
}
}
10-25
835
835
08-17
843
843
02-15
1万+
1万+


被折叠的 条评论
为什么被折叠?



