實際上關于asp.net驗證碼制作的文章已經很多很多了,但是今天還是要和大家繼續分享,親,可以綜合幾篇實例,編寫出適用于自己網站的ASP.NET驗證碼,大概也就兩大部分:
protected void Page_Load(object sender, EventArgs e)
{
string validateCode = CreateValidateCode();//生成驗證碼
Bitmap bitmap = new Bitmap(imgWidth,imgHeight);//生成Bitmap圖像
DisturbBitmap(bitmap); //圖像背景
DrewValidateCode(bitmap,validateCode);//繪制驗證碼圖像
bitmap.Save(Response.OutputStream,ImageFormat.Gif);//保存圖像,等待輸出
}
private int codeLen = 4;//驗證碼長度
private int fineness = 85;//圖片清晰度
private int imgWidth = 48;//圖片寬度
private int imgHeight = 24;//圖片高度
private string fontFamily = "Times New Roman";//字體名稱
private int fontSize = 14;//字體大小
//private int fontStyle = 0;//字體樣式
private int posX = 0;//繪制起始坐標X
private int posY = 0;//繪制坐標Y
private string CreateValidateCode() //生成驗證碼
{
string validateCode = "";
Random random = new Random();// 隨機數對象
for (int i = 0; i codeLen; i++)//循環生成每位數值
{
int n = random.Next(10);//數字
validateCode += n.ToString();
}
Session["vcode"] = validateCode;//保存驗證碼 這Session是在前臺調用的。
return validateCode;// 返回驗證碼
}
private void DisturbBitmap(Bitmap bitmap)//圖像背景
{
Random random = new Random();//通過隨機數生成
for (int i = 0; i bitmap.Width; i++)//通過循環嵌套,逐個像素點生成
{
for (int j = 0; j bitmap.Height; j++)
{
if (random.Next(90) = this.fineness)
bitmap.SetPixel(i, j, Color.LightGray);
}
}
}
private void DrewValidateCode(Bitmap bitmap, string validateCode)//繪制驗證碼圖像
{
Graphics g = Graphics.FromImage(bitmap);//獲取繪制器對象
Font font = new Font(fontFamily, fontSize, FontStyle.Bold);//設置繪制字體
g.DrawString(validateCode, font, Brushes.Black, posX, posY);//繪制驗證碼圖像
}
//這個函數是在點擊驗證碼圖片就會更換驗證碼
//可以使用微軟自帶的jqury.js 下面jquery-1.4.1.min.js版本之上的。或者在jquery官網上下載就可以。
script src="styles/jquery-1.4.1.min.js" type="text/javascript">/script>
function f_refreshtype() {
var Image1 = document.getElementByIdx_x_x_x("img");
if (Image1 != null) {
Image1.src = Image1.src + "?";
}
}
---img src="ValidateCode.aspx" id="img" onclick="f_refreshtype()" width="50px"/>//調用函數,實現更換驗證碼