.Net WebAPI 生成图形验证码
1.安装nuget SkiaSharp
2.创建 VerifyCodeHelper帮助类
using SkiaSharp; namespace WebApplication3 { 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] 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 = 1, Image = "data:image/png;base64," + Convert.ToBase64String(arr) }); }
原文地址: https://blog.csdn.net/weixin_46193339/article/details/128074161
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验