- 安装nuget SkiaSharp
- 创建 VerifyCodeHelper帮助类
public class VerifyCodeHelper
{
public static byte[] GetVerifyCode(string text)
{
int width = 74;
int height = 36;
Random random = new();
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()
{
Random rad = new Random();
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) });
}