欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ValidNumber.ashx验证码

程序员文章站 2022-03-30 21:56:39
validnumber.ashx 代码: <%@ webhandler language="c#" class="validnumber&qu...

validnumber.ashx 代码:

<%@ webhandler language="c#" class="validnumber" %>

using system;
using system.web;
using system.web.sessionstate; //第一步:导入此命名空间
public class validnumber : ihttphandler, irequiressessionstate
{

    public void processrequest(httpcontext context)
    {
        //种子
        string[] strlist = new[]
        {
            "a","b","c","d","1","2","3","4","5","6","7","8","9","0","q","w","e","r","t","y","u","i","o","p","z","x","n","v","w","q","b","a","d","d","f","g","h","j","k","l"
        };

        //生成随机数
        string[] list = new string[4];
        random rd = new random(datetime.now.millisecond * 100000);
        for (int i = 0; i < 4; i++)
        {
            list[i] = strlist[rd.next(strlist.length)];
            system.threading.thread.sleep(5);
        }

        system.text.stringbuilder sb = new system.text.stringbuilder();
        for (int i = 0; i < 4; i++)
        {
            sb = sb.append(list[i]);
        }
        httpcontext.current.session["validnumber"] = sb;
        //创建一张图片
        system.drawing.bitmap image = new system.drawing.bitmap(list.length * 15, 40);
        //创建画布
        system.drawing.graphics g = system.drawing.graphics.fromimage(image);
        //清空背景色,并添充成白色
        g.clear(system.drawing.color.white);

        //噪声线
        for (int i = 0; i < 20; i++)
        {
            random rds = new random();

            float x1 = rds.next(image.width - 1);
            float x2 = rds.next(image.width - 1);
            float y1 = rds.next(image.height - 1);
            float y2 = rds.next(image.height - 1);
            system.threading.thread.sleep(5);
            g.drawline(new system.drawing.pen(system.drawing.color.silver), x1, y1, x2, y2);
        }
        system.drawing.font f = new system.drawing.font("黑体", 25, system.drawing.graphicsunit.pixel);
        system.drawing.brush bs = new system.drawing.solidbrush(system.drawing.color.red);

        g.drawstring(sb.tostring(), f, bs, 5, 5);
        //当前请求输出的类型
        httpcontext.current.response.contenttype = "image/jpeg";
        //保存到输出流
        image.save(httpcontext.current.response.outputstream, system.drawing.imaging.imageformat.jpeg);

        g.dispose();
        image.dispose();

    }

    public bool isreusable
    {
        get
        {
            return false;
        }
    }

}

页面调用时 <img src="validnumber.ashx" alt="图片验证码" /> 但是回发session值改变页面图片没变,暂无比较理想的解决办法,提交时后台用  response.write("<script> window.location.href=window.location.href</script>")  刷新下页面。欢迎指教,有没有好点的用法。

 


摘自 bql_email的专栏