今天在項目裡面要寫一個登陸頁面,既然是登陸頁面,肯定少不了驗證碼圖片,所以今天就在前人的指引下,寫了一個生成驗證碼圖片的功能廢話不多說,實現了打開登陸頁面是生成驗證碼圖片以及點擊驗證碼時,刷新驗證碼功能,驗證碼中既包含26個小寫字母,也包含10個阿裡伯數字,直接看代碼: html代碼: <img i ...
今天在項目裡面要寫一個登陸頁面,既然是登陸頁面,肯定少不了驗證碼圖片,所以今天就在前人的指引下,寫了一個生成驗證碼圖片的功能廢話不多說,實現了打開登陸頁面是生成驗證碼圖片以及點擊驗證碼時,刷新驗證碼功能,驗證碼中既包含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();
}
實現效果: