首页 .NET/Web asp.net算术验证码的生成与实现

asp.net算术验证码的生成与实现

作者:胡同里的砖头 围观群众:1864 更新于:2013-12-19



protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            string randomcode = getcodeInit();
            
            this.CreateImage(randomcode);
           
        }
    }
    /// <summary>
    /// 
    /// </summary>
    protected string getcodeInit() 
    {
        Random rand = new Random();
        string[] chu = new string [4];
        chu[0] = "+";
        chu[1] = "-";
        chu[2] = "*";
        chu[3] = "/";
        int randnum1 = rand.Next(10); //除数
        int randnum2 = rand.Next(10);//被除数

        int num3 = rand.Next(4);//定义算数方式0加法1减法2乘法3除法
        if(num3==3)
        {
            while(randnum2==0)
            {
                randnum1 = rand.Next(10);
                randnum2 = rand.Next(10);
            }
        }
        if(randnum1==0)
        {
            randnum1 = rand.Next(10);
            randnum2 = rand.Next(10);
        }
        string opera = chu[num3].ToString();
        int result = -1;
        switch(opera)
        {
            case "+":
                result = randnum1 + randnum2;
                break;
            case "-":
                result = randnum1 - randnum2;
                break;
            case "*":
                result = randnum1 * randnum2;
                break;
            case "/":
                result = randnum1 / randnum2;
                break;
        }
        Session["result"] = result;
        string ret = randnum1 + opera + randnum2 + "=" + "?";
        return ret;

    }
    /// <summary>
    /// 创建随机码图片
    /// </summary>
    /// <param name="randomcode">随机码</param>
    private void CreateImage(string randomcode)
    {
        int randAngle = 30; //随机转动角度
        int mapwidth = (int)(randomcode.Length * 32);
        Bitmap map = new Bitmap(mapwidth, 28);//创建图片背景
        Graphics graph = Graphics.FromImage(map);
        graph.Clear(Color.AliceBlue);//清除画面,填充背景
        graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框
        //graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//模式

        Random rand = new Random();
        //背景噪点生成
        Pen blackPen = new Pen(Color.LightGray, 0);
        for (int i = 0; i < 50; i++)
        {
            int x = rand.Next(0, map.Width);
            int y = rand.Next(0, map.Height);
            graph.DrawRectangle(blackPen, x, y, 1, 1);
        }

        //验证码旋转,防止机器识别
        char[] chars = randomcode.ToCharArray();//拆散字符串成单字符数组
        //文字距中
        StringFormat format = new StringFormat(StringFormatFlags.NoClip);
        format.Alignment = StringAlignment.Center;
        format.LineAlignment = StringAlignment.Center;
        //定义颜色
        Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
        //定义字体 
        string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
        for (int i = 0; i < chars.Length; i++)
        {
            int cindex = rand.Next(7);
            int findex = rand.Next(5);
            Font f = new System.Drawing.Font(font[findex], 13, System.Drawing.FontStyle.Bold);//字体样式(参数2为字体大小)
            Brush b = new System.Drawing.SolidBrush(c[cindex]);
            Point dot = new Point(23, 16);
            //graph.DrawString(dot.X.ToString(),fontstyle,new SolidBrush(Color.Black),10,150);//测试X坐标显示间距的
            float angle = rand.Next(-randAngle, randAngle);//转动的度数
            graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置
            graph.RotateTransform(angle);
            graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);
            //graph.DrawString(chars[i].ToString(),fontstyle,new SolidBrush(Color.Blue),1,1,format);
            graph.RotateTransform(-angle);//转回去
            graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置
        }
        //graph.DrawString(randomcode,fontstyle,new SolidBrush(Color.Blue),2,2); //标准随机码

        //生成图片
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        Response.ClearContent();
        Response.ContentType = "image/gif";
        Response.BinaryWrite(ms.ToArray());
        graph.Dispose();
        map.Dispose();
    }


 

//调用页面:

<script type="text/javascript">  
        function refreshimg(){
  var img = document.getElementById("verImg");
  
  img.src="code.aspx?"+Math.random();
  }   
  
</script>

<div>
   
    <img src="code.aspx" id="verImg" name="verImg" /><a href='javascript:refreshimg()' title='看不清楚,换张图片'><font color='blue'>换一张</font></a>
    <br />
     请输入验证码: <input id="txtcode" style="width:80px;" runat="server" name="txtcode"/>
    <br />
    <input type="button" id="btngetresult" runat="server" value="获取" onserverclick="btngetresult_onServerClick" />
    </div>

 

  • 本文标题: asp.net算术验证码的生成与实现
  • 文章分类:【.NET/Web】
  • 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.
留言评论
站点声明:
1、本站【胡同里的砖头】个人博客,借鉴网上一些博客模板,取其各优点模块自行拼装开发,本博客开发纯属个人爱好。
2、所有笔记提供给广大用户交流使用,可转载,可复制,纯个人开发所遇问题锦集记录使用
Copyright © huzlblog.com All Rights Reserved. 备案号:苏ICP备2021056683号-8