GDI+之验证码

来源:互联网 发布:bot的知识图谱数据api 编辑:程序博客网 时间:2024/05/23 11:59

1、简单验证码:

  • html:
    <img src="ValidateCode.ashx?" id="vcode" onclick="ChangeCode()" />    <a href="javascript:ChangeCode();">看不清换一张</a>
  • 脚本:
    <script type="text/javascript">        function ChangeCode() {            var src1 = document.getElementById("vcode").src;            document.getElementById("vcode").src = src1+1;        }    </script>
  • 后台ashx:
        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            //创建画布            Bitmap bm = new Bitmap(400, 120);            //获取绘制工具            Graphics g = Graphics.FromImage(bm);            //随机生成验证码字符串            string src = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";            string des = "";            Random r = new Random();            for (int i = 0; i < 6; i++)            {                des += src[r.Next(src.Length)];            }            //绘制            g.Clear(Color.White);            g.DrawRectangle(new Pen(Color.Black), 10, 10, 380, 100);            g.DrawString(des, new Font("微软雅黑", 60), new SolidBrush(Color.Green), 0, 0);            //保存:将画布保存到流中,而不是保存到物理文件中            bm.Save(context.Response.OutputStream, ImageFormat.Jpeg);        }

2、使用封装好的验证码操作类

ValidateCode

  • ashx:
        public void ProcessRequest(HttpContext context)        {            context.Response.ContentType = "text/plain";            ValidateCodeHelper vcode = new ValidateCodeHelper();            string strvcode = vcode.CreateValidateCode(6);            vcode.CreateValidateGraphic(strvcode, context);        }
0 0
原创粉丝点击