我们在设计用户登录模块时,经常会用到验证码,可以有效地防止黑客软件的恶意破解,现公开我常用的验证码的源代码。
使用方法:
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">生成字母的个数</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://记录上次随机数值,尽量避免生产几个一样的随机数
file://采用一个简单的算法以保证生成随机数的不同
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 ;
}
}
新闻热点
疑难解答
图片精选