.Net中验证码图片生成
今天在项目里面要写一个登陆页面,既然是登陆页面,肯定少不了验证码图片,所以今天就在前人的指引下,写了一个生成验证码图片的功能废话不多说,实现了打开登陆页面是生成验证码图片以及点击验证码时,刷新验证码功能,验证码中既包含26个小写字母,也包含10个阿里伯数字,直接看代码:
html代码:
<img id="vivaverificationImg" src="@Url.Action("CreateCheckCodeImage", "VerificationCode")" onclick="vivaChangeVerificationCodeSrc(this)"/>
js代码:
function vivaChangeVerificationCodeSrc(obj) {
host = window.location.host;
obj.src = "http://" + host + "/VerificationCode/CreateCheckCodeImage?seed=" + Math.random();
}
C#代码
/// <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();
}
实现效果:
下一篇: lombok简介