C# 随机生成验证码

使用C#根据需要的验证码长度,随机生成验证码

public class AuthcodeHelper
{
/// <summary>
/// 获取验证码
/// </summary>
/// <param name="length">验证码长度</param>
/// <returns>返回生成的验证码字符串</returns>
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;
}
/// <summary>
/// 获取图片验证码
/// </summary>
/// <param name="authcode"></param>
/// <param name="imageWidth"></param>
/// <param name="imageHeight"></param>
/// <returns></returns>
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;
}
}
}
posted @   M&Fx  阅读(300)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示