js
<img id="validateCode_img" src="/handerashx/VerifyCode.ashx" width="90" height="25" class="mr10" style="vertical-align: middle;"/><a href="javascript:changeImage()">换一组</a> </br>
<%--为a标签注册验证码事件--%>
<script type="text/javascript">
function changeImage() {
document.getElementById("validateCode_img").src = document.getElementById("validateCode_img").src + '?';
}
</script>
一般处理程序制作验证码
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.SessionState;//添加命名空间,用于保存session
namespace LiBangWuLiu
{
/// <summary>
/// VerifyCode 的摘要说明
/// </summary>
public class VerifyCode : IHttpHandler,IRequiresSessionState //实现IRequiresSessionState
{
/// <summary>
/// 创建一副图片,画上验证码
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/plain";//响应类型为图片image
string validateCode = getValidateCode(4);//获取一个四位数字的验证码
context.Session["validateCode"] = validateCode;//将验证码存到session中,
//创建验证码图片
using (Bitmap img = new Bitmap(60, 28))//创建具体位置图像,位图
{
using (Graphics g = Graphics.FromImage(img))//从指定的img创建新的图面)
{
g.Clear(Color.LightYellow);//初始化图片背景色
g.DrawRectangle(new Pen(Color.Red), 0, 0, img.Width - 1, img.Height - 1);//画图片上矩形的边框,从坐标(0,0)开始,相对于图片的坐标
Font font = new System.Drawing.Font("Arial", 16, (System.Drawing.FontStyle.Bold));//字体样式
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Blue, Color.DarkRed, 1.2F, true);//渐变效果
g.DrawString(validateCode, font, brush, 2, 2);//将验证码写入图片
//画前景线 ,随机生成几个点,(x1,y1)到(x2,y2)画线
Random ran = new Random();
int i;
for (i = 0; i < 10; i++)
{
int x1 = ran.Next(img.Width);
int x2 = ran.Next(img.Width);
int y1 = ran.Next(img.Height);
int y2 = ran.Next(img.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
}
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);//将图片保存到响应流
//string yanzhengma1 = context.Request.QueryString["yzm"];
//context.Response.Write(yanzhengma(validateCode,yanzhengma1));//返回产生的随机数
//context.Response.End();
}
}
bool falg = false;
public bool yanzhengma(string sjm,string yzm)
{
if (sjm == yzm)
{
falg = true;
}
else {
falg = false;
}
return falg;
}
/// <summary>
/// 生成随机码的方法,
/// </summary>
/// <param name="validateCodeLength">随机码的长度</param>
/// <returns>随机码</returns>
private string getValidateCode(int validateCodeLength)
{
string allchar =@"123456789qwertyuioplkjhgfdsazxcvbnm123456789QWERTYUIOPLKJHGFDSAZXCVBNM";//列出所有可能出现的字符
int length = allchar.Length;//获取所有字符的个数
Random ran = new Random();//声明生成一个随机数的对象
string validateCode = string.Empty;//声明随机码
for (int i = 0; i < validateCodeLength; i++)
{
validateCode += allchar[ran.Next(length)];//找到随机码,用生成的随机数作为字符串的索引,下标
}
return validateCode;
}
public bool IsReusable
{
get
{
return false;
}
}
}
}