商业源码热门下载www.html.org.cn
收藏一段小的.net下的验证码片段,以供以后参考。
protected void page_load(object sender, eventargs e)
{
//先产生数字串
string checkcode = this.createrandomcode(6);
//用session保存
session["checkcode"] = checkcode;
//作图
createimage(checkcode);
}
private void createimage(string checkcode)
{
system.drawing.bitmap image = new system.drawing.bitmap(convert.toint32(math.ceiling((decimal)(checkcode.length * 14))), 22);
graphics g = graphics.fromimage(image);
try
{
random random = new random();
g.clear(color.aliceblue);
for (int i = 0; i < 25; i++)
{
int x1 = random.next(image.width);
int x2 = random.next(image.width);
int y1 = random.next(image.height);
int y2 = random.next(image.height);
g.drawline(new pen(color.silver), x1, y1, x2, y2);
}
font font = new system.drawing.font("comic sans ms", 12, system.drawing.fontstyle.bold);
system.drawing.drawing2d.lineargradientbrush brush = new system.drawing.drawing2d.lineargradientbrush(new rectangle(0, 0, image.width, image.height), color.blue, color.darkred, 1.2f, true);
g.drawstring(checkcode, font, new solidbrush(color.red), 2, 2);
for (int i = 0; i < 100; i++)
{
int x = random.next(image.width);
int y = random.next(image.height);
image.setpixel(x, y, color.fromargb(random.next()));
}
g.drawrectangle(new pen(color.silver), 0, 0, image.width - 1, image.height - 1);
system.io.memorystream ms = new system.io.memorystream();
image.save(ms, system.drawing.imaging.imageformat.gif);
response.clearcontent();
response.contenttype = "image/gif";
response.binarywrite(ms.toarray());
}
finally
{
g.dispose();
image.dispose();
}
}
public string createrandomcode(int codecount)
{
string allchar = "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,q,r,s,t,u,v,w,x,y,z";
string[] allchararray = allchar.split(',');
string randomcode = "";
int temp = -1;
random rand = new random();
for (int i = 0; i < codecount; i++)
{
if (temp != -1)
{
rand = new random(i * temp * ((int)datetime.now.ticks));
}
int t = rand.next(36);
if (temp != -1 && temp == t)
{
return createrandomcode(codecount);
}
temp = t;
randomcode += allchararray[t];
}
return randomcode;
}
新闻热点
疑难解答
图片精选