用一般处理程序做的图片验证码

新建一般处理程序:ValidateImageHandler.ashx

<%@ WebHandler Language="C#" Class="ValidateImageHandler" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;

/// <summary>
/// ValidateImageHandler 生成网站验证码功能
/// </summary>
public class ValidateImageHandler : IHttpHandler, IRequiresSessionState
{
    int intLength = 5;               //长度
    string strIdentify = "Identify"; //随机字串存储键值,以便存储到Session中
    public ValidateImageHandler()
    {
    }

    /// <summary>
    ///  生成验证图片核心代码
    /// </summary>
    /// <param name="hc"></param>
    public void ProcessRequest(HttpContext hc)
    {
        //设置输出流图片格式
        hc.Response.ContentType = "image/gif";

        Bitmap b = new Bitmap(200, 60);
        Graphics g = Graphics.FromImage(b);
        g.FillRectangle(new SolidBrush(Color.YellowGreen), 0, 0, 200, 60);
        Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
        Random r = new Random();

        //合法随机显示字符列表
        string strLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder s = new StringBuilder();

        //将随机生成的字符串绘制到图片上
        for (int i = 0; i < intLength; i++)
        {
            s.Append(strLetters.Substring(r.Next(0, strLetters.Length - 1), 1));
            g.DrawString(s[s.Length - 1].ToString(), font, new SolidBrush(Color.Blue), i * 38, r.Next(0, 15));
        }

        //生成干扰线条
        Pen pen = new Pen(new SolidBrush(Color.Blue), 2);
        for (int i = 0; i < 10; i++)
        {
            g.DrawLine(pen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
        }
        b.Save(hc.Response.OutputStream, ImageFormat.Gif);
        hc.Session[strIdentify] = s.ToString(); //先保存在Session中,验证与用户输入是否一致
        hc.Response.End();

    }

    /// <summary>
    /// 表示此类实例是否可以被多个请求共用(重用可以提高性能)
    /// </summary>
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
}
调用:
<script language="javascript" type="text/javascript">
    <!--
        function ChangeCode()
        {
            document.all.verifyCode.src="ValidateImageHandler.ashx?"+Math.random();
        }
    -->
</script>

<img id="verifyCode" width="80px" height="20px" src="ValidateImageHandler.ashx" /><a style="cursor:hand;" οnclick="ChangeCode();">看不清,换一张?</a>
运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值