using System.Drawing;
using System.Web;
using System.Web.SessionState;
<%@ WebHandler Language="C#" Class="LoginVode" %>
using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
public class LoginVode : IHttpHandler,IRequiresSessionState {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "image/jpeg";
//生成随机验证码
string strVcode = MakeCode();
//将 验证码 保存在Session中
context.Session["vcode"] = strVcode;
using (Bitmap img = new Bitmap(120, 30))
{
//创建 画家 对象
using (Graphics g = Graphics.FromImage(img))
{
//填充一个矩形
//g.FillRectangle(Brushes.White, 1, 1, img.Width-2, img.Height-2);
g.FillRectangle(Brushes.White, 0, 0, img.Width, img.Height);
//画上一个 矩形 边框
g.DrawRectangle(Pens.Red, 0, 0, img.Width-2, img.Height-2);
//作画
g.DrawString(strVcode, new Font("微软雅黑", 12), Brushes.Black, 0, 0);
img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
}
public string MakeCode()
{
string strCode = string.Empty;
Random ran = new Random();
for (int i = 0; i < 5; i++)
{
strCode += codeArr[ran.Next(codeArr.Length)];
}
return strCode;
}
string[] codeArr = {
"3","4","5","6","7","8","9","1","2","a","b","c"
};
public bool IsReusable {
get {
return false;
}
}
}
以上是生成验证码的页面
然后在HTML上写这个img标签。可是显示不了图片啊。。。
<img alt="Loading" title="点击换验证码" onclick="this.src='../ashx/LoginVode.ashx?i='+new Date();" src="../ashx/LoginVode.ashx" />
刷新下流,context.Response.End()试下
试了一把,可以正常显示,楼主是否路径写错了。在浏览其中直接浏览LoginVode.ashx试一下呢。