前言:
验证码技术已愈来愈成熟,从最初的数字、字母、字符、汉字已经到目前的语言,其应用也甚广。针对这个问题,可简单可讲究:
1、简单的思路:一个label+随机数(数字|字母|特殊符号等)的显示
2、稍微讲究的思路:一个Image控件+显示验证码图片
3、 汉字:选字验证码
正文:
那么首先说下第一种:
第一种方法的本质:C#生成随机数(字母或数字)
/// <summary>
///声明一个静态变量
/// </summary>
private static char[] constant =
{
'0','1','2','3','4','5','6','7','8','9',
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
};
/// <summary>
/// 静态方法
/// </summary>
/// <returns>return一个string类型的随机数</returns>
public static string GenerateRandomNumber()
{
System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
Random rd = new Random();
for (int i = 0; i < 4; i++)
{
newRandom.Append(constant[rd.Next(62)]);
}
return newRandom.ToString();
}
第二种方法:生成string类型的验证码的方式和第一种本质相同,第二种方法的重点在得到string类型验证码的基础上是创建验证码的图片
/// <summary>
/// 创建验证码的图片
/// </summary>
/// <param name="containsPage">要输出到的page对象</param>
/// <param name="validateNum">验证码</param>
public byte[] CreateValidateGraphic(string validateCode)
{
Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的干扰线
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(validateCode, font, brush, 3, 2);
//画图片的前景干扰点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
}
//画图片的边框线
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
//保存图片数据
MemoryStream stream = new MemoryStream();
image.Save(stream, ImageFormat.Jpeg);
//输出图片流
return stream.ToArray();
}
finally
{
g.Dispose();
image.Dispose();
}
}
提供一个完整代码供大家参考,本质都相同:点击打开链接拓展:
汉字:选字验证码 - CSDN博客https://blog.csdn.net/saindy5828/article/details/75410434