Ajax动态刷新验证码图片

时间:2023-03-08 21:49:25
Ajax动态刷新验证码图片

一》 原理:

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

二》 步骤

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

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

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

    4. 想前台返回路径

三》 代码实例如下

Identifying.html 代码

 <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>验证码实验</title>
<script src="jquery-1.4.1.js"></script>
</head>
<body>
验证码:
<div>
<img src="" id="tp"/><a href="javascript:void(0)" id="huan">看不清换一张</a>
</div>
<script type="text/javascript">
$(function () {
function xx() {
$.ajax({
url: 'Identif.ashx',
type: 'POST',
datatype: 'text',
success: function (data) {
$("#tp").attr("src", data.toString());
}
});
};
xx();
$("#huan").click(xx);
});
</script>
</body>
</html>

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(, ); //创建位图文件
Graphics g = Graphics.FromImage(map); //画布 //填充背景颜色
g.FillRectangle(Brushes.White, , , , ); //随机产生验证码
string code = null;
Random re = new Random(Guid.NewGuid().GetHashCode()); //用哈希数做随机种子
for(int i = ; i < ; i++)
{
if (re.Next(, ) % == )
{
code += re.Next(, ).ToString();
}
else
{
code+= (Char)re.Next(, );
}
} //删除已存在的文件
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("宋体", ), Brushes.Gray, new PointF(, ));
//绘制干扰点
Random random = new Random();
for (int i = ; i<; i++)
{
map.SetPixel(random.Next(, ), random.Next(, ), Color.LightGray);
} //输出图像
map.Save(path); //发送相对路径
context.Response.Write("../"+code+".jpg"); context.Response.End(); } public bool IsReusable
{
get
{
return false;
}
}
}
}