項目需要,要在首頁登錄界面添加一個圖形驗證碼,趕時髦吧,網(wǎng)上一搜,特別多,找了幾個,都不太滿意。主要問題是大部分代碼生成的圖片寬度不唯一,頁面布局不容易控制,其次是顏色單一,有些又過于抽象,不仔細看很容易弄錯。針對特定的客戶,我只需要“圖片”長寬固定,顏色多樣的數(shù)字圖形驗證碼,借鑒網(wǎng)上的現(xiàn)有代碼,自己操刀完成,以下是效果圖:
原理不復雜,就是把網(wǎng)頁當畫布,運用各色畫筆,在特定區(qū)域內(nèi)畫出數(shù)字,然后以特定格式(本例為png格式)發(fā)回客戶端,在ie中顯示為"圖片",用于驗證的字符串存于session中。
主要代碼如下:
// 生成隨機數(shù)字字符串
public string getrandomnumberstring(int int_numberlength)
{
string str_number = string.empty;
random therandomnumber = new random();
for (int int_index = 0; int_index < int_numberlength; int_index++)
str_number += therandomnumber.next(10).tostring();
return str_number;
}
生成隨機顏色
public color getrandomcolor()
{
random randomnum_first = new random((int)datetime.now.ticks);
// 對于c#的隨機數(shù),沒什么好說的
system.threading.thread.sleep(randomnum_first.next(50));
random randomnum_sencond = new random((int)datetime.now.ticks);
// 為了在白色背景上顯示,盡量生成深色
int int_red = randomnum_first.next(256);
int int_green = randomnum_sencond.next(256);
int int_blue = (int_red + int_green > 400) ? 0 : 400 - int_red - int_green;
int_blue = (int_blue > 255) ? 255 : int_blue;
return color.fromargb(int_red, int_green, int_blue);
}
根據(jù)驗證字符串生成最終圖象
public void createimage(string str_validatecode)
{
int int_imagewidth = str_validatecode.length * 13;
random newrandom = new random();
// 圖高20px
bitmap thebitmap = new bitmap(int_imagewidth, 20);
graphics thegraphics = graphics.fromimage(thebitmap);
// 白色背景
thegraphics.clear(color.white);
// 灰色邊框
thegraphics.drawrectangle(new pen(color.lightgray, 1), 0, 0, int_imagewidth - 1, 19);
// 10pt的字體
font thefont = new font("arial", 10);
for (int int_index = 0; int_index < str_validatecode.length; int_index++)
{
string str_char = str_validatecode.substring(int_index, 1);
brush newbrush = new solidbrush(getrandomcolor());
point thepos = new point(int_index * 13 + 1 + newrandom.next(3), 1 + newrandom.next(3));
thegraphics.drawstring(str_char, thefont, newbrush, thepos);
}
// 將生成的圖片發(fā)回客戶端
memorystream ms = new memorystream();
thebitmap.save(ms, imageformat.png);
response.clearcontent(); //需要輸出圖象信息 要修改http頭
response.contenttype = "image/png";
response.binarywrite(ms.toarray());
thegraphics.dispose();
thebitmap.dispose();
response.end();
}
最后在page_load中調(diào)用以上代碼
private void page_load(object sender, system.eventargs e)
{
if(!ispostback)
{
// 4位數(shù)字的驗證碼
string str_validatecode = getrandomnumberstring(4);
// 用于驗證的session
session["validatecode"] = str_validatecode;
createimage(str_validatecode);
}
}
使用的時候在頁面中加入一個image,將圖片路徑改為validatecode.aspx的相對路徑即可
<img src="validatecode.aspx" />在需要驗證的地方填入如下代碼:
if (textbox1.text == session["validatecode"].tostring())
{
textbox1.text = "正確!";
}
else
textbox1.text = "錯誤!";
ok,基本搞定,總結一下:
優(yōu)點:
1. 簡單明了,適于簡單運用
2. 界面友好,圖片長寬格式固定
缺點:
1. 如果有多個頁面都需要此驗證碼,則會導致session被其它頁面重寫的情況,可以考慮指定具體session值為效驗值
2. 暫時只支持數(shù)字,不過更改getrandomnumberstring()中的代碼可以實現(xiàn)指定字符機的隨機字符串
3. 頁面刷新后驗證碼隨之改變
拋磚引玉,歡迎各位博友評點
新聞熱點
疑難解答
圖片精選