asp.net生成图片验证码的例子

发布时间:2020-05-29编辑:脚本学堂
为大家介绍一个asp.net生成图片验证码的例子,适合初学的朋友参考。

1、创建文件 image.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

protected void Page_Load(object sender, EventArgs e)
{
     //生成4位的验证码

     stringtmp=RndNum(4);

     HttpCookiea=newHttpCookie("ImageV",tmp);

     Response.Cookies.Add(a);

     this.ValidateCode(tmp);

    }  

    /// <summary>
    /// 将参数以图片的形式显示出来
    /// </summary>
    /// <param name="VNum"></param>
    private void ValidateCode(string VNum)
     {
         Bitmap Img = null;
         Graphics g = null;
         MemoryStream ms = null;

         int gheight = VNum.Length * 12;
         Img = new Bitmap(gheight, 30);
         g = Graphics.FromImage(Img);
         //背景颜色
         g.Clear(Color.WhiteSmoke);
         //文字字体
         Font f = new Font("Arial Black", 12);
         //文字颜色
         SolidBrush s = new SolidBrush(Color.RoyalBlue);
         g.DrawString(VNum, f, s, 1, 3);
         ms = new MemoryStream();
         Img.Save(ms, ImageFormat.Jpeg);
         Response.ClearContent();
         Response.ContentType = "image/jpeg";
         Response.BinaryWrite(ms.ToArray());
         g.Dispose();
         Img.Dispose();
         Response.End();
     }

privatestringRndNum(intVcodeNum)
{
stringVchar="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(newChar[]{','});

stringVNum="";
inttemp=-1;
Randomrand=newRandom();

for(inti=1;i<VcodeNum+1;i++)
{
if(temp!=-1)
{
rand=newRandom(i*temp*unchecked((int)DateTime.Now.Ticks));
}
intt=rand.Next(35);

if(temp!=-1&&temp==t)
{
returnRndNum(VcodeNum);
}
temp=t;
VNum+=VcArray[t];
}
returnVNum;

}

2、调用方法
在要生成验证码的页面添加一个图片控件,假设命名为:ImageButton1,然后在page_Load事件中加入:

mageButton1.ImageUrl="image.aspx";

就可以使用这个验证码了。