zoukankan      html  css  js  c++  java
  • ASP.NET中登陆验证码的生成和输入验证码的验证

    一:验证码的生成实现代码

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

        }

        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;//保存验证码 这Session是在前台调用的。
            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);//绘制验证码图像
        }

    二:登陆时验证验证码的正确性

      if (TextBox1.Text.ToUpper().Equals(Session["vcode"]+ ""))【Session["vcode"]为生成验证码时保存的session值】

    让技术改变未来,让技术影响人们生活方式
  • 相关阅读:
    致初学者:PHP比ASP优秀的七个理由
    有情人终成眷属为好友hualex2006.12.9结婚祝福
    有情人终成眷属为好友hualex2006.12.9结婚祝福
    各种查找算法效率比较
    实习三 树、二叉树及其应用 (题目:唯一地确定一棵二叉树 )
    hdu 2188 选拔志愿者(博弈)
    hdu 1050Moving Tables(贪心)
    实习一 线性表及其应用 (题目:一元稀疏多项式的加法运算 )
    实习六 农夫过河问题
    实习二 栈、队列和递归算法设计 (题目:停车场管理 )
  • 原文地址:https://www.cnblogs.com/huangtaiyu/p/5813844.html
Copyright © 2011-2022 走看看