首页 > 编程 > .NET > 正文

asp.net 生成图片验证码

2024-07-10 13:10:46
字体:
来源:转载
供稿:网友

identifyingcode.aspx里没有内容略。
identifyingcode.cs文件:
using system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
using system.drawing;
using system.drawing.imaging;
using system.io;
public partial class identifyingcode : system.web.ui.page
{
    protected void page_load(object sender, eventargs e)
    {
        string tmp = rndnum(4);
        httpcookie a = new httpcookie("imagev", tmp);
        response.cookies.add(a);
        this.validatecode(tmp);

    }
    private void validatecode(string vnum)
    {
        bitmap img = null;
        graphics g = null;
        memorystream ms = null;

        int gheight = vnum.length * 12;
        img = new bitmap(gheight, 25);
        g = graphics.fromimage(img);
        //背景颜色
        g.clear(color.lightsteelblue);
        //文字字体
        font f = new font("arial black", 10);
        //文字颜色
        solidbrush s = new solidbrush(color.royalblue);
        g.drawstring(vnum, f, s, 3, 3);
        ms = new memorystream();
        img.save(ms, imageformat.jpeg);
        response.clearcontent();
        response.contenttype = "images/jpeg";
        response.binarywrite(ms.toarray());
        g.dispose();
        img.dispose();
        response.end();
    }

    private string rndnum(int vcodenum)
    {
        string vchar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p" +
        ",q,r,s,t,u,v,w,x,y,z";
        string[] vcarray = vchar.split(new char[] { ',' });
        string vnum = "";
        int temp = -1;

        random rand = new random();

        for (int i = 1; i < vcodenum + 1; i++)
        {
            if (temp != -1)
            {
                rand = new random(i * temp * unchecked((int)datetime.now.ticks));
            }

            int t = rand.next(35);
            if (temp != -1 && temp == t)
            {
                return rndnum(vcodenum);
            }
            temp = t;
            vnum += vcarray[t];
        }
        return vnum;
    }

}
 
使用方法:
在需要它的页面html里添加
 <img src="identifyingcode.aspx" />
 

  httpcookiecollection cookies = request.cookies;
  string tmp = cookies["imagev"].value;
  然后比tmp与获取的较验证码文本框中的值是否相同

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表