首页 > 代码库 > ASP.NET产生随机验证码

ASP.NET产生随机验证码

效果图:(Flowing)

1、项目中新建用于存储(位图)图片文件夹

图解:

2、前台可以添加一ASP.NET控件或其他任意用来展示图片标签等(如下)

    <div>        <asp:Image ID="Image1" runat="server" ImageUrl="../img/RandomImg.gif" />    </div>

3、产生随机数(如下)

        /// <summary>        /// 产生随机数        /// </summary>        /// <param name="codeLength"></param>        /// <returns></returns>        public string CreateCode(int codeLength)        {            //这里本人没做是否允许重复控制,读者需要可做相应控制            string so = "1,2,3,4,5,6,7,8,9,0,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,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[] strArr = so.Split(,);            string code = "";            Random rand = new Random();            for (int i = 0; i < codeLength; i++)            {                code += strArr[rand.Next(0, strArr.Length)];            }            return code;        }

4、产生验证图片(如下)

        /// <summary>        /// 产生验证图片        /// </summary>        /// <param name="code"></param>        public void CreateImage(string code)        {            //建立位图对象,(70,25)位图大小控制            Bitmap image = new Bitmap(70, 25);            //根据上面创建的位图对象创建绘图层            Graphics g = Graphics.FromImage(image);            WebColorConverter ww = new WebColorConverter();            g.Clear((Color)ww.ConvertFromString("#FAE264"));//产生位图背景色            Random random = new Random();            //画图片的背景噪音线            for (int i = 0; i < 12; 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.Green), x1, y1, x2, y2);//Color.LightGray噪音线颜色            }            //创建字体对象            Font font = new Font("Arial", 15, FontStyle.Bold | FontStyle.Italic);            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(                new Rectangle(0, 0, image.Width, image.Height), Color.Red, Color.Gray, 1.2f, true);            g.DrawString(code, font, brush, 0, 0);            //画图片的边框线            g.DrawRectangle(new Pen(Color.Green), 0, 0, image.Width - 0, image.Height - 0);            //临时保存(位图)图片            image.Save(Server.MapPath("../img") + "\\RandomImg.gif", System.Drawing.Imaging.ImageFormat.Gif);         }

5、调用(如下)(注意:这里本人仅是为了做测试,读者亦要考虑局部刷新问题,这里本人先不做出详解)

        protected void Page_Load(object sender, EventArgs e)        {            string checkCode = CreateCode(4);//4代表要产生随机数个数            Session["CheckCode"] = checkCode;            CreateImage(checkCode);        }

 欢迎指正,提出更好的方法-wvqusrtg