
在一些项目中,需要在用户注册或者登录时提示输入验证码,那么如何在ASP.NET中实现验证码的功能呢?
1.知识点介绍
验证码其实是随机产生的一些数字,在System命名空间下提供的Random类可以用来产生随机性的非负数字.
在ASP.NET中的System.Drawing命名空间中,提供了Bitmap,Graphics类,其中Bitmap类封装了GDI+位图,继承自Image类,用于处理由像素数据定义的图象.Graphics类封装了GDI和绘图面,也就是相当于画板.下面就使用Random,Bitmap和Graphics类把生成的随即数绘制到创建的位图中.并用Image控件显示创建的位图.
2.示例
新建"WebForm1.aspx"页面,在该页面中添加一个Image控件,并设置其ImageUrl属性为生成的位图所要存放的路径.
(1)WebForm1.aspx.cs代码:
 private void Page_Load(object sender, System.EventArgs e)
private void Page_Load(object sender, System.EventArgs e) {
        {     //建立位图对象
            //建立位图对象 Bitmap newBitmap=new Bitmap(36,16,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Bitmap newBitmap=new Bitmap(36,16,System.Drawing.Imaging.PixelFormat.Format32bppArgb); //根据上面创建的位图对象创建绘图层
            //根据上面创建的位图对象创建绘图层 Graphics g=Graphics.FromImage(newBitmap);
            Graphics g=Graphics.FromImage(newBitmap); //以指定的颜色填宠矩形区
            //以指定的颜色填宠矩形区 g.FillRectangle(new SolidBrush(Color.White),new Rectangle(0,0,36,16));
            g.FillRectangle(new SolidBrush(Color.White),new Rectangle(0,0,36,16)); //创建字体对象
            //创建字体对象 Font textFont=new Font("Times new Roman",10);
            Font textFont=new Font("Times new Roman",10); //创建RectangleF结构指定一个区域
            //创建RectangleF结构指定一个区域 RectangleF rectangle=new RectangleF(0,0,36,16);
            RectangleF rectangle=new RectangleF(0,0,36,16); //创建随机数对象
            //创建随机数对象 Random rd=new Random();
            Random rd=new Random(); //取得随机数
            //取得随机数 int valationNo=1000+rd.Next(8999);
            int valationNo=1000+rd.Next(8999); //使用指定的颜色填充上面的RectangleF结构指定的矩形区域
            //使用指定的颜色填充上面的RectangleF结构指定的矩形区域 g.FillRectangle(new SolidBrush(Color.BurlyWood),rectangle);
            g.FillRectangle(new SolidBrush(Color.BurlyWood),rectangle); //在上面填充的矩形区域中填充上面生成的随机数
            //在上面填充的矩形区域中填充上面生成的随机数 g.DrawString(valationNo.ToString(),textFont,new SolidBrush(Color.Blue),rectangle);
            g.DrawString(valationNo.ToString(),textFont,new SolidBrush(Color.Blue),rectangle); //把创建的位图保存到指定的路径
            //把创建的位图保存到指定的路径 newBitmap.Save(Server.MapPath("img")+"\\RandomImg.gif",System.Drawing.Imaging.ImageFormat.Gif);
            newBitmap.Save(Server.MapPath("img")+"\\RandomImg.gif",System.Drawing.Imaging.ImageFormat.Gif); }
        }首先创建Bitmap和Graphics对象,然后通过Font和RectangleF对象把Random对象生成的随机数绘制到位图上,最后把创建的位图保存到指定的目录下.
注:首先运行程序,把img目录下生成的RandomImg.gif图片包括在工程中,然后设置页面Image的ImageUrl属性=RandomImg.gif.
 
                    
                 
 
        
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号