asp.net创建位图生成验证图片类(验证码类)
代码:
public void processrequest(httpcontext context)
{
context.response.contenttype = "image/jpeg";
//创建位图,并且给指定边框的宽高
using (image img=new bitmap(80,25))
{
//创建画家对象,在img对象画字符串
using (graphics g=graphics.fromimage(img))
{
//设置位图的背景颜色,默认是黑色
g.clear(color.white);
//设置验证码的宽高, img.width-1, img.height-1主要是背景颜色覆盖了边框线
g.drawrectangle(pens.black, 0, 0, img.width-1, img.height-1);
//传100个噪点,传画家对象,位图对象
drawpoint(100, g, img);
//画4个验证码的字符串
string vcode=getcode(4);//vcode这里可以赋值给cookie
g.drawstring(vcode,
new font("arial", 14, fontstyle.strikeout | fontstyle.strikeout), // fontstyle字体的样式,多个样式,需要|线
brushes.black,
new rectanglef(r.next(20), r.next(7), img.width, img.height));
img.save(context.response.outputstream, system.drawing.imaging.imageformat.jpeg);//保存验证码对象,指定是jpeg格式
}
}
}
//画噪点方法
void drawpoint(int point,graphics g,image img)
{
for (int i = 0; i < point; i++)
{
int x = r.next(img.width);
int y = r.next(img.width);
g.drawline(pens.red,
new point(x, y),
new point(x+2, y+2));
}
}
//随机数
random r = new random();
//画字符创
string getcode(int point)
{
string txtstr = "asf2345we5r9f3hmbcz455k";//这里的string字符串将会转成 char数组,阿拉伯数字1和小写字母l最好别写在里面,会搞胡乱。
char[] chararr = txtstr.toarray();
int num = 0;
string code = "";
for (int i = 0; i <point; i++)
{
num = r.next(chararr.length);
code +=chararr[num];
}
return code;
}
上一篇: C#中属性和成员变量的区别说明