加入收藏 | 设为首页 | 会员中心 | 我要投稿 大连站长网 (https://www.0411zz.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > Asp教程 > 正文

asp.net 简单验证码验证实现代码

发布时间:2021-07-13 10:59:55 所属栏目:Asp教程 来源:互联网
导读:首先是新建一个验证码页面 ValidateCode.aspx 定义变量 这样有利于后期的修改了 复制代码 代码如下: private int codeLen = 4;//验证码长度 private int fineness = 85;//图片清晰度 private int imgWidth = 48;//图片宽度 private int imgHeight = 24;//图
首先是新建一个验证码页面 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);//绘制验证码图像
}


最后就是调用了

复制代码 代码如下:


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


ValidateCode.aspx页面完成
剩下就简单了 新建一个页面

复制代码 代码如下:


<asp:Image runat="server" ImageUrl="~/Default2.aspx" ImageAlign="Middle" />


运行后的效果如图:

提交的时候将文本框里面的值与Session["vcode"] = validateCode;//保存验证码 比较就可以判断输入是否正确了

(编辑:大连站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读