.Net中验证码图片生成

时间:2023-01-14 04:23:29

开发网站或平台系统,登录页面是必不可少的功能,但是现在很多人可以使用工具暴力破解网站密码,为了防止这类非法操作,需要在登录页面添加验证,验证码就是最常用的一种验证方式。

我结合了自己的经验和网上的验证码资料,总结一下c#验证码开发,直接放代码,文中有注释,可以轻松理解代码意思。

功能:实现了打开登陆页面是生成验证码图片以及点击验证码时,刷新验证码功能,验证码中既包含26个小写字母,也包含10个阿里伯数字(这里都可以自定义)

html和JavaScript代码:

<img id="vivaverificationImg" src="@Url.Action("CreateCheckCodeImage", "VerificationCode")" onclick="vivaChangeVerificationCodeSrc(this)"/>

function vivaChangeVerificationCodeSrc(obj) {
  host = window.location.host;
  obj.src = "http://" + host + "/VerificationCode/CreateCheckCodeImage?seed=" + Math.random();
}

C#代码(VerificationCode.cs):

/// <summary>
/// 生成验证码图片
/// </summary> public void CreateCheckCodeImage()
{
string checkCode = VerficationCodeSrc(); if (checkCode == null || checkCode.Trim() == String.Empty)
return; //string checkCode = "asfd2";
Bitmap image = new Bitmap(, ); Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = ; i < ; 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.Black), x1, y1, x2, y2);
}
Font font = new Font("Arial", , (FontStyle.Bold)); System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(, , image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true); g.DrawString(checkCode, font, brush, , );
//画图片的前景噪音点
for (int i = ; i < ; 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), , , image.Width - , image.Height - );
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
} /// <summary>
/// 生成验证码字符串
/// </summary>
/// <param name="numberOfChars"></param>
/// <returns></returns>
private string VerficationCodeSrc(int numberOfChars)
{
if (numberOfChars > )
{
throw new InvalidOperationException("Random Word Charecters can not be greater than 36.");
}
char[] columns = new char[];
//字母
for (int charPos = ; charPos < + ; charPos++)
columns[charPos - ] = (char)charPos;
//数字
for (int intPos = ; intPos <= ; intPos++)
columns[intPos - ] = (char)intPos; StringBuilder randomBuilder = new StringBuilder();
Random randomSeed = new Random();
for (int incr = ; incr < numberOfChars; incr++)
{
randomBuilder.Append(columns[randomSeed.Next()].ToString());
} return randomBuilder.ToString();
}

实现效果:

.Net中验证码图片生成

如果你觉得我写的对你有用,请给个推荐,如果有什么疑问,请留言。