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

C#工具:ASP.NET MVC生成图片验证码

程序员文章站 2022-10-06 13:54:54
1、复制下列代码,拷贝到控制器中。 2、复制以下图片标记到视图中 3、验证方式,使用 Session["SecurityCode"] 判断填写的是否相等,txtCode自己输入的验证码。 ......

1、复制下列代码,拷贝到控制器中。

#region  生成验证码图片
        // [outputcache(location = outputcachelocation.none, duration = 0, nostore = false)]
        public actionresult securitycode()
        {

            string oldcode = session["securitycode"] as string;
            string code = createrandomcode(5);
            session["securitycode"] = code;
            return file(createvalidategraphic(code), "image/jpeg");
        }


        private byte[] createimage(string checkcode)
        {
            int iwidth = (int)(checkcode.length * 12);
            system.drawing.bitmap image = new system.drawing.bitmap(iwidth, 20);
            graphics g = graphics.fromimage(image);
            font f = new system.drawing.font("arial", 10, system.drawing.fontstyle.bold);
            brush b = new system.drawing.solidbrush(color.white);
            g.clear(color.blue);
            g.drawstring(checkcode, f, b, 3, 3);
            pen blackpen = new pen(color.black, 0);
            random rand = new random();
            for (int i = 0; i < 5; i++)
            {
                int x1 = rand.next(image.width);
                int x2 = rand.next(image.width);
                int y1 = rand.next(image.height);
                int y2 = rand.next(image.height);
                g.drawline(new pen(color.silver, 1), x1, y1, x2, y2);
            }
            system.io.memorystream ms = new system.io.memorystream();
            image.save(ms, system.drawing.imaging.imageformat.jpeg);
            return ms.toarray();
        }

        private string createrandomcode(int codecount)
        {
            string allchar = "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,w,x,y,z";
            string[] allchararray = allchar.split(',');
            string randomcode = "";
            int temp = -1;
            random rand = new random();
            for (int i = 0; i < codecount; i++)
            {
                if (temp != -1)
                {
                    rand = new random(i * temp * ((int)datetime.now.ticks));
                }
                int t = rand.next(35);
                if (temp == t)
                {
                    return createrandomcode(codecount);
                }
                temp = t;
                randomcode += allchararray[t];
            }
            return randomcode;
        }
        /// <summary>
        /// 创建验证码的图片
        /// </summary>
        public byte[] createvalidategraphic(string validatecode)
        {
            bitmap image = new bitmap((int)math.ceiling(validatecode.length * 16.0), 27);
            graphics g = graphics.fromimage(image);
            try
            {
                //生成随机生成器
                random random = new random();
                //清空图片背景色
                g.clear(color.white);
                //画图片的干扰线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.next(image.width);
                    int x2 = random.next(image.width);
                    int y1 = random.next(image.height);
                    int y2 = random.next(image.height);
                    g.drawline(new pen(color.silver), x1, y1, x2, y2);
                }
                font font = new font("arial", 13, (fontstyle.bold | fontstyle.italic));
                lineargradientbrush brush = new lineargradientbrush(new rectangle(0, 0, image.width, image.height),
                 color.blue, color.darkred, 1.2f, true);
                g.drawstring(validatecode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.next(image.width);
                    int y = random.next(image.height);
                    image.setpixel(x, y, color.fromargb(random.next()));
                }
                //画图片的边框线
                g.drawrectangle(new pen(color.silver), 0, 0, image.width - 1, image.height - 1);
                //保存图片数据
                memorystream stream = new memorystream();
                image.save(stream, imageformat.jpeg);
                //输出图片流
                return stream.toarray();
            }
            finally
            {
                g.dispose();
                image.dispose();
            }
        }
        #endregion

2、复制以下图片标记到视图中

<img src="/控制器的名字/securitycode" onclick="this.src+='?new date()'" />

3、验证方式,使用 session["securitycode"] 判断填写的是否相等,txtcode自己输入的验证码。

           if (session["securitycode"] .tostring().tolower() != txtcode.tolower())
                {
                    response.write("<script>alert('验证码错误')</script>");
                }
                else
                {
                 
                }