public class Captcha
{
public static string randomCode = "";//随机验证码字符串
private readonly int width = 90;//验证码宽度
private readonly int height = 35;//验证码长度
private readonly int codeLength = 4;//验证码位数
private readonly Color[] Colors = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Brown, Color.Purple };
private readonly char[] Chars = { '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
///
/// 绘制验证码
///
///
public byte[] GetCaptcha()
{
var code = GetRandomText(codeLength);
var r = new Random();
using var image = new Image(width, height);
var font = SystemFonts.CreateFont(SystemFonts.Families.First().Name, 25, FontStyle.Bold);
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((this.width - 10) * i / code.Length + 5, r.Next(this.height / 5, this.height / 4))
);
}
for (int i = 0; i < 5; i++)
{
var pen = new Pen(Colors[r.Next(Colors.Length)], 1);
var p1 = new PointF(r.Next(width), r.Next(height));
var p2 = new PointF(r.Next(width), r.Next(height));
ctx.DrawLines(pen, p1, p2);
}
for (int i = 0; i < 20; i++)
{
var pen = new Pen(Colors[r.Next(Colors.Length)], 1);
var p1 = new PointF(r.Next(width), r.Next(height));
var p2 = new PointF(p1.X + 1f, p1.Y + 1f);
ctx.DrawLines(pen, p1, p2);
}
});
using var ms = new System.IO.MemoryStream();
image.SaveAsPng(ms);
return ms.ToArray();
}
///
/// 获取随机数
///
///
///
private string GetRandomText(int length)
{
var code = string.Empty;
var r = new Random();
for (int i = 0; i < length; i++)
{
code += Chars[r.Next(Chars.Length)].ToString();
}
randomCode = code;
return code;
}
}
///
/// 获取图片验证码
///
///
[AllowAnonymous]
[HttpGet]
public IActionResult GetCaptcha()
{
var bytes = new Captcha().GetCaptcha();
return File(bytes,@"image/gif");
}