直接上code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
namespace AnalyzerExtAuth.Common
{
public partial class ValidateCodeImg : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//驗證碼中可能會出現的字符集合
String checkCodeString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//驗證碼字符集合的長度
int length = checkCodeString.Length;
//設置繪製驗證碼的字體,並設置爲粗體並傾斜
Font font = new Font("宋體", 24, (FontStyle.Bold | FontStyle.Italic));
//繪製驗證碼的筆刷
Brush brush = null;
//繪製驗證碼文字的顏色
Color brushColor = new Color();
//驗證碼的字符串
String checkCode = String.Empty;
//當前要繪製的驗證字符
String code = String.Empty;
//要生成的驗證碼圖片對象
Bitmap image = new Bitmap(80, 40);
//繪圖畫板
Graphics graphics = Graphics.FromImage(image);
//填充背景爲白色
graphics.Clear(Color.White);
//創建隨機數對象
Random random = new Random();
int x1, x2, y1, y2;
Pen pen = new Pen(Color.Silver);
//畫背景噪音線
for (int i = 1; i <= 25; i++)
{
x1 = random.Next(image.Width);
y1 = random.Next(image.Height);
x2 = random.Next(image.Width);
y2 = random.Next(image.Height);
graphics.DrawLine(pen, x1, y1, x2, y2);
}
for (int i = 0; i < 4; i++)
{
//爲了保證取的字符索引不超過0-35之間
//取任何數的餘數都肯定小於自身
//採用當前時間的毫秒 % 驗證碼字符的總長度=當前驗證字符
int current = random.Next(DateTime.Now.Millisecond) % length;
//截取驗證字符
code = checkCodeString.Substring(current, 1);
//拼接到驗證碼的字符串
checkCode += code;
//隨機生成驗證碼字符的顏色
brushColor = Color.FromArgb(random.Next(256), random.Next(256), random.Next(256));
//筆刷的顏色
brush = new SolidBrush(brushColor);
//繪製剛剛得到的字符串
graphics.DrawString(code, font, brush, i * 15 + 2, 2);
}
Response.Clear();
Response.ContentType = "image/pjpeg";
//在Session中保存驗證碼字符串,以便與用戶輸入進行比較
Session["CheckCode"] = checkCode;
image.Save(Response.OutputStream, ImageFormat.Jpeg);
image.Dispose();
Response.End();
}
}
}
//驗證控件
< img src = "ValidateCode.aspx" width = "60" height = "25" style = "cursor: pointer;" onclick = "this.src='ValidateCode.aspx?id'+Math.random()*10000" / >
P.S.其中id加上一個隨機數只是爲了網頁能夠刷新重新計算驗證碼。當然我們還可以在後面添加生成驗證碼的長度,以便更好的管理驗證碼複雜性