使用C#根据需要的验证码长度,随机生成验证码
| public class AuthcodeHelper |
| { |
| |
| |
| |
| |
| |
| |
| public static string GetRandomAuthcode(int length) |
| { |
| |
| string chkCode = string.Empty; |
| |
| |
| char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' }; |
| |
| Random rnd = new Random(); |
| |
| for (int i = 0; i < length; i++) |
| { |
| chkCode += character[rnd.Next(character.Length)]; |
| } |
| |
| return chkCode; |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| public static MemoryStream GetImage(string authcode, int imageWidth = 110, int imageHeight = 30) |
| { |
| try |
| { |
| |
| Color[] color = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.Brown, Color.DarkBlue }; |
| |
| string[] font = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" }; |
| Random rnd = new Random(); |
| Bitmap bmp = new Bitmap(imageWidth, imageHeight); |
| Graphics g = Graphics.FromImage(bmp); |
| g.Clear(Color.White); |
| |
| for (int i = 0; i < 4; i++) |
| { |
| int x1 = rnd.Next(imageWidth); |
| int y1 = rnd.Next(imageHeight); |
| int x2 = rnd.Next(imageWidth); |
| int y2 = rnd.Next(imageHeight); |
| Color clr = color[rnd.Next(color.Length)]; |
| g.DrawLine(new Pen(clr), x1, y1, x2, y2); |
| } |
| |
| for (int i = 0; i < authcode.Length; i++) |
| { |
| string fnt = font[rnd.Next(font.Length)]; |
| Font ft = new Font(fnt, 14); |
| Color clr = color[rnd.Next(color.Length)]; |
| g.DrawString(authcode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 8, (float)4); |
| } |
| |
| for (int i = 0; i < 20; i++) |
| { |
| int x = rnd.Next(bmp.Width); |
| int y = rnd.Next(bmp.Height); |
| Color clr = color[rnd.Next(color.Length)]; |
| bmp.SetPixel(x, y, clr); |
| } |
| g.DrawRectangle(new Pen(Color.Blue, 1), 0, 0, bmp.Width - 1, bmp.Height - 1); |
| |
| MemoryStream ms = new MemoryStream(); |
| try |
| { |
| bmp.Save(ms, ImageFormat.Png); |
| } |
| finally |
| { |
| |
| bmp.Dispose(); |
| g.Dispose(); |
| } |
| |
| return ms; |
| } |
| catch (Exception ex) |
| { |
| Console.WriteLine(ex.Message); |
| return null; |
| } |
| |
| } |
| |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了