码迷,mamicode.com
首页 > Web开发 > 详细

ASP.NET实现验证码

时间:2015-06-24 18:56:27      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

这里首先说一下原理

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

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

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);//保存图像,等待输出 
} 



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

技术分享



ASP.NET实现验证码

标签:

原文地址:http://blog.csdn.net/u012965373/article/details/46624395

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!