asp.net 生成图片验证码
[来源 www.iocblog.net]
1 protected void page_load(object sender, eventargs e) 2 { 3 string tmp = rndnum(4); 4 httpcookie a = new httpcookie("imagev", tmp); 5 response.cookies.add(a); 6 this.validatecode(tmp); 7 } 8 private void validatecode(string vnum) 9 { 10 bitmap img = null; 11 graphics g = null; 12 memorystream ms = null; 1314 int gheight = vnum.length * 12; 15 img = new bitmap(gheight, 25); 16 g = graphics.fromimage(img); 17 //背景颜色18 g.clear(color.lightsteelblue); 19 //文字字体20 font f = new font("arial black", 10); 21 //文字颜色22 solidbrush s = new solidbrush(color.royalblue); 23 g.drawstring(vnum, f, s, 3, 3); 24 ms = new memorystream(); 25 img.save(ms, imageformat.jpeg); 26 response.clearcontent(); 27 response.contenttype = "images/jpeg"; 28 response.binarywrite(ms.toarray()); 29 g.dispose(); 30 img.dispose(); 31 response.end(); 32 } 3334 private string rndnum(int vcodenum) 35 { 36 string vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p" +37 ",q,r,s,t,u,v,w,x,y,z"; 38 string[] vcarray = vchar.split(new char[] { ',' }); 39 string vnum = ""; 40 int temp = -1; 4142 random rand = new random(); 4344 for (int i = 1; i < vcodenum + 1; i++) 45 { 46 if (temp != -1) 47 { 48 rand = new random(i * temp * unchecked((int)datetime.now.ticks)); 49 } 5051 int t = rand.next(35); 52 if (temp != -1 && temp == t) 53 { 54 return rndnum(vcodenum); 55 } 56 temp = t; 57 vnum += vcarray[t]; 58 } 59 return vnum; 60 }
使用方法:
在需要它的页面html里添加
<img src="identifyingcode.aspx" />
httpcookiecollection cookies = request.cookies;
string tmp = cookies["imagev"].value;[来源 www.iocblog.net]
然后比tmp与获取的较验证码文本框中的值是否相同
Tag: 验证码
文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。