Ajax动态刷新验证码图片

一》 原理:

  把用代码生成的图片存放到硬盘当中,然后在返回存储路径把图片通过图片标签的 src 属性 自动加载到浏览器中 

二》 步骤

    1. 首先用GDI+ 绘图 把验证码图片给绘制出来

    2. 然后提前判断硬盘里是否有已生成的图片,如果有,则删除,以避免节省硬盘空间

    3. 把生成的验证码存放到 Session 会话当中,以供前台验证 填写验证码的准确性, 在构建文件路径,把验证码图片存入路径中

    4. 想前台返回路径

三》 代码实例如下

Identifying.html 代码

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 5     <title>验证码实验</title>
 6     <script src="jquery-1.4.1.js"></script>
 7 </head>
 8 <body>
 9     验证码:
10     <div>
11         <img src="" id="tp"/><a href="javascript:void(0)" id="huan">看不清换一张</a>
12     </div>
13     <script type="text/javascript">
14         $(function () {
15             function xx() {
16                 $.ajax({
17                     url: 'Identif.ashx',
18                     type: 'POST',
19                     datatype: 'text',
20                     success: function (data) {
21                         $("#tp").attr("src", data.toString());
22                     }
23                 });
24             };
25             xx();
26             $("#huan").click(xx);
27         });
28     </script>
29 </body>
30 </html>
View Code

Identif.ashx 代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing;
using System.Web.SessionState;

namespace FourmWeb.Identifying
{
    /// <summary>
    /// Identif 的摘要说明
    /// </summary>
    public class Identif : IHttpHandler,IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";//响应报文主体的类型            

            string path = context.Request.MapPath("~/"); ;
            Bitmap map = new Bitmap(60, 20); //创建位图文件
            Graphics g = Graphics.FromImage(map); //画布

            //填充背景颜色
            g.FillRectangle(Brushes.White, 1, 1, 58, 18);


            //随机产生验证码
            string code = null;
            Random re = new Random(Guid.NewGuid().GetHashCode());   //用哈希数做随机种子
            for(int i = 0; i < 4; i++)
            {
                if (re.Next(1, 101) % 2 == 0)
                {
                    code += re.Next(0, 10).ToString();
                }
                else
                {
                    code+= (Char)re.Next(65, 91);
                }
            } 
            
            //删除已存在的文件
            if (context.Session["code"] != null)
            File.Delete(path + context.Session["code"].ToString() + ".jpg");
            
            //构建文件路径
            path += code + ".jpg";
          
           context.Session["code"] = code;

            //将验证码画到画布上
            g.DrawString(code, new Font("宋体", 12), Brushes.Gray, new PointF(4, 2));
            //绘制干扰点
            Random random = new Random();
            for (int i = 0; i<200; i++)
            {
                map.SetPixel(random.Next(1, 60), random.Next(1, 18), Color.LightGray);
            }

            //输出图像
            map.Save(path);

            //发送相对路径
            context.Response.Write("../"+code+".jpg");  

            context.Response.End();
            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
View Code

      

原文地址:https://www.cnblogs.com/haizeiwen/p/3652522.html