.Net中验证码图片生成

开发网站或系统,都需要有一个登录页面,肯定也少不了验证码图片,来防止被暴力破解密码,我总结了一下自己的经验,写一下验证码功能。

功能:实现了打开登陆页面是生成验证码图片以及点击验证码时,刷新验证码功能,验证码中既包含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(5);

if (checkCode == null || checkCode.Trim() == String.Empty)
return;

//string checkCode = "asfd2";
Bitmap image = new Bitmap(90, 28);

Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器 
Random random = new Random();
//清空图片背景色 
g.Clear(Color.White);
//画图片的背景噪音线 
for (int i = 0; i < 2; 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", 16, (FontStyle.Bold));

System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);

g.DrawString(checkCode, font, brush, 2, 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);
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 > 36)
{
throw new InvalidOperationException("Random Word Charecters can not be greater than 36.");
}
char[] columns = new char[36];
//字母
for (int charPos = 97; charPos < 97 + 26; charPos++)
columns[charPos - 97] = (char)charPos;
//数字
for (int intPos = 48; intPos <= 57; intPos++)
columns[intPos - 22] = (char)intPos;

StringBuilder randomBuilder = new StringBuilder();
Random randomSeed = new Random();
for (int incr = 0; incr < numberOfChars; incr++)
{
randomBuilder.Append(columns[randomSeed.Next(36)].ToString());
}

return randomBuilder.ToString();
}

实现效果:

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

posted @ 2018-05-30 17:24 laoyang01 阅读(...) 评论(...) 编辑 收藏