- 下载包nuget SkiaSharp
- 创建帮助类 VerificationCodeHelper
点击查看代码
public class VerifyCodeHelper
{
/// <summary>
/// 获取图像数字验证码
/// </summary>
/// <param name="text">验证码内容,如4为数字</param>
/// <returns></returns>
public static byte[] GetVerifyCode(string text)
{
int width = 74;
int height = 36;
Random random = new();
//创建bitmap位图
using SKBitmap image = new(width, height, SKColorType.Bgra8888, SKAlphaType.Premul);
//创建画笔
using SKCanvas canvas = new(image);
//填充背景颜色为白色
canvas.DrawColor(SKColors.White);
//颜色列表
SKColor[] colors = { SKColors.Black, SKColors.Red, SKColors.Blue, SKColors.Green, SKColors.Orange, SKColors.Brown, SKColors.DarkBlue };
//画图片的背景噪音线
for (int i = 0; i < 20; i++)
{
using SKPaint drawStyle = new();
drawStyle.Color = colors[random.Next(colors.Length)];
canvas.DrawLine(random.Next(0, width), random.Next(0, height), random.Next(0, width), random.Next(0, height), drawStyle);
}
//将文字写到画布上
using (SKPaint drawStyle = new())
{
drawStyle.TextSize = height;
drawStyle.StrokeWidth = 1;
float emHeight = height - (float)height * (float)0.14;
float emWidth = ((float)width / text.Length) - ((float)width * (float)0.13) + 5;
for (int i = 0; i < text.Length; i++)
{
drawStyle.Color = colors[random.Next(colors.Length)];
var jg = (width - (emWidth * text.Length)) / text.Length - 1;
//画在画板上
canvas.DrawText(text[i].ToString(), emWidth * i + jg, emHeight, drawStyle);
}
}
//画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
image.SetPixel(random.Next(0, width), random.Next(0, height), colors[random.Next(colors.Length)]);
}
using var img = SKImage.FromBitmap(image);
using SKData p = img.Encode(SKEncodedImageFormat.Png, 100);
return p.ToArray();
}
}
- 调用
点击查看代码
[HttpGet("ObtainImageVerificationCode")]
[CustomAnonymousFiler]
public IActionResult ObtainImageVerificationCode()
{
//var images = ImageVerificationCode.CreateVerifyCode(4, VerifyCodeType.NUM);
Random rad = new Random(); //实例化随机数产生器rad;
int value = rad.Next(1000, 10000);
var arr = VerifyCodeHelper.GetVerifyCode(value.ToString());
return Ok(new { Id = key, Image = "data:image/png;base64," + Convert.ToBase64String(arr) });
}