首先创建一个一般处理程序,添加代码如下:
public class Handler1 : IHttpHandler,System.Web.SessionState.IRequiresSessionState
{
private static Random random = new Random();
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
Image image = new Bitmap(60, 30);
//随即产生一个四位数
int code = random.Next(1000, 10000);
string codeString = code.ToString();
//验证码放进Session中以便代码回传的时候验证用户输入的验证码是否正确
context.Session["Code"] = codeString;
using (Graphics g = Graphics.FromImage(image))
{
g.Clear(Color.WhiteSmoke);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString(codeString,new Font("Arial",14),Brushes.Blue,new RectangleF(0,0,image.Width,image.Height),sf);
image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
在asp页面中调用上面的处理程序:
<asp:Image ID="Image1" runat="server" ImageUrl="~/Handler1.ashx" />
以上代码就OK了。