天天看點

如何在asp.net中動态生成驗證碼(轉)

現在越來越多的網站喜歡搞個驗證碼出來,而且各個語言基本上都能做到,今天我來一個C#寫的!

using System;

using System.Collections;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Web;

using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

using System.Drawing.Imaging;

using System.Drawing.Drawing2D;

//建立位圖對象

public void randomNumber()

{

   Bitmap newBitmap = new Bitmap(36,16,PixelFormat.Format32bppArgb);

   //根據上面建立的位圖對象建立繪圖面

   Graphics g = Graphics.FromImage(newBitmap);

   //以指定的顔色填充矩形區

   g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0,0,36,16));

   //建立字型對象

   Font textFont = new Font("Times New Roman",10);

   //建立RectangleF結構指定一個區域

   RectangleF rectangle = new RectangleF(0,0,36,16);

   //建立随機數對象

   Random rd = new Random();

   //取得随機數

   int valationNo = 1000 + rd.Next(8999);

   //使用指定的顔色填充上面RectangleF結構指定的矩形區域

   g.FillRectangle(new SolidBrush(Color.BurlyWood), rectangle);

   //在上面填充的矩形區域中填充上面生成的随機數

   g.DrawString(valationNo.ToString(), textFont, new SolidBrush(Color.Blue), rectangle);

   //把建立的位圖儲存到指定的路徑

   newBitmap.Save(Server.MapPath("img")+"\\Img.gif", ImageFormat.Gif);

}

生成以後在前台頁面裡引入這個圖檔的位址就可以了!

繼續閱讀