我們在設(shè)計用戶登錄模塊時,經(jīng)常會用到驗證碼,可以有效地防止黑客軟件的惡意破解,現(xiàn)公開我常用的驗證碼的源代碼。
使用方法:
1、在web項目中添加一個類,如“createimage.cs”,然后將我公布的源代碼copy進去;
2、再新建一個web窗體,如“image.aspx”,在page_load中加入代碼“createimage.drawimage ();”當然別忘了加上對類的引用哦!!
3、在頁面的合適位置上(你想放驗證碼的位置)上加上如下javascript代碼就ok 了,
<script language="javascript">
<!--
var numkey = math.random();
numkey = math.round(numkey*10000);
document.write("<img src=/"image.aspx?k="+ numkey +"/" width=/"52/" height=/"23/" hspace=/"4/"");
file://->
</script>
源代碼如下:
/// <summary>
/// 驗證碼模塊
/// </summary>
public class createimage
{
public static void drawimage()
{
createimage img=new createimage();
httpcontext.current.session["checkcode"]=img.rndnum(4);
img.createimages(httpcontext.current.session["checkcode"].tostring());
}
/// <summary>
/// 生成驗證圖片
/// </summary>
/// <param name="checkcode">驗證字符</param>
private void createimages(string checkcode)
{
int iwidth = (int)(checkcode.length * 13);
system.drawing.bitmap image = new system.drawing.bitmap(iwidth, 23);
graphics g = graphics.fromimage(image);
g.clear(color.white);
file://定義顏色
color[] c = {color.black,color.red,color.darkblue,color.green,color.orange,color.brown,color.darkcyan,color.purple};
file://定義字體
string[] font = {"verdana","microsoft sans serif","comic sans ms","arial","宋體"};
random rand = new random();
file://隨機輸出噪點
for(int i=0;i<50;i++)
{
int x = rand.next(image.width);
int y = rand.next(image.height);
g.drawrectangle(new pen(color.lightgray, 0),x,y,1,1);
}
file://輸出不同字體和顏色的驗證碼字符
for(int i=0;i<checkcode.length;i++)
{
int cindex = rand.next(7);
int findex = rand.next(5);
font f = new system.drawing.font(font[findex], 10, system.drawing.fontstyle.bold);
brush b = new system.drawing.solidbrush(c[cindex]);
int ii=4;
if((i+1)%2==0)
{
ii=2;
}
g.drawstring(checkcode.substring(i,1), f, b, 3+(i*12), ii);
}
file://畫一個邊框
g.drawrectangle(new pen(color.black,0),0,0,image.width-1,image.height-1);
file://輸出到瀏覽器
system.io.memorystream ms = new system.io.memorystream();
image.save(ms,system.drawing.imaging.imageformat.jpeg);
httpcontext.current.response.clearcontent();
file://response.clearcontent();
httpcontext.current.response.contenttype = "image/jpeg";
httpcontext.current.response.binarywrite(ms.toarray());
g.dispose();
image.dispose();
}
/// <summary>
/// 生成隨機的字母
/// </summary>
/// <param name="vcodenum">生成字母的個數(shù)</param>
/// <returns>string</returns>
private string rndnum(int vcodenum)
{
string vchar = "0,1,2,3,4,5,6,7,8,9" ;
string[] vcarray = vchar.split(',') ;
string vnum = "" ; file://由于字符串很短,就不用stringbuilder了
int temp = -1 ; file://記錄上次隨機數(shù)值,盡量避免生產(chǎn)幾個一樣的隨機數(shù)
file://采用一個簡單的算法以保證生成隨機數(shù)的不同
random rand =new random();
for ( int i = 1 ; i < vcodenum+1 ; i++ )
{
if ( temp != -1)
{
rand =new random(i*temp*unchecked((int)datetime.now.ticks));
}
int t = rand.next(vcarray.length ) ;
if (temp != -1 && temp == t)
{
return rndnum( vcodenum );
}
temp = t ;
vnum += vcarray[t];
}
return vnum ;
}
}
新聞熱點
疑難解答
圖片精選