- 下载包nuget SkiaSharp
- 创建帮助类 VerificationCodeHelper
点击查看代码
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) });
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构