这里首先说一下原理

在一个登录界面中,放一个image在界面上,然后添加一个新项,起名为validatecode.x页面

添加一个新的页面,在新建的页面中写入如下代码:

 

private int codelen = 4;//验证码长度 
private int fineness = 85;//图片清晰度 
private int imgwidth = 48;//图片宽度 
private int imgheight = 24;//图片高度 
private string fontfamily = "times new roman";//字体名称 
private int fontsize = 14;//字体大小 
private int fontstyle = 0;//字体样式 
private int posx = 0;//绘制起始坐标x 
private int posy = 0;//绘制坐标y 
private string createvalidatecode() //生成验证码 
{ 
string validatecode = ""; 
random random = new random();// 随机数对象 
for (int i = 0; i < codelen; i++)//循环生成每位数值 
{ 
int n = random.next(10);//数字 
validatecode += n.tostring(); 
} 
session["vcode"] = validatecode;//保存验证码 
return validatecode;// 返回验证码 
} 
private void disturbbitmap(bitmap bitmap)//图像背景 
{ 
random random = new random();//通过随机数生成 
for (int i = 0; i < bitmap.width; i++)//通过循环嵌套,逐个像素点生成 
{ 
for (int j = 0; j < bitmap.height; j++) 
{ 
if (random.next(90) <= this.fineness) 
bitmap.setpixel(i,j,color.lightgray); 
} 
} 
} 
private void drewvalidatecode(bitmap bitmap,string validatecode)//绘制验证码图像 
{ 
graphics g = graphics.fromimage(bitmap);//获取绘制器对象 
font font = new font(fontfamily,fontsize,fontstyle.bold);//设置绘制字体 
g.drawstring(validatecode,font,brushes.black,posx,posy);//绘制验证码图像 
} 

 

然后在page_load(object sender, eventargs e) 中写入:

 

 

protected void page_load(object sender, eventargs e) 
{ 
string validatecode = createvalidatecode();//生成验证码 
bitmap bitmap = new bitmap(imgwidth,imgheight);//生成bitmap图像 
disturbbitmap(bitmap); //图像背景 
drewvalidatecode(bitmap,validatecode);//绘制验证码图像 
bitmap.save(response.outputstream,imageformat.gif);//保存图像,等待输出 
} 

 

 

最后运行代码,出现如下样式: