新建一個頁面image.ASPx,添加命名空間:
using System.Drawing.Imaging;
using System.IO;
然後在Page_load事件拷入如下代碼:
//生成4位的驗證碼
string tmp = RndNum(4);
HttpCookie a = new HttpCookIE("ImageV",tmp);
Response.CookIEs.Add(a);
this.ValidateCode(tmp);
接下來向該頁面添加兩個方法:
private void ValidateCode(string VNum)
{
Bitmap Img=null;
Graphics g=null;
MemoryStream ms=null;
int gheight=VNum.Length*12;
Img=new Bitmap(gheight,25);
g=Graphics.FromImage(Img);
//背景顏色
g.Clear(Color.White);
//文字字體
Font f=new Font("Arial Black",10);
//文字顏色
SolidBrush s=new SolidBrush(Color.Black);
g.DrawString(VNum,f,s,3,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();
}
private string RndNum(int VcodeNum)
{
string Vchar="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(new Char [] {','});
string VNum="";
int temp=-1;
Random rand=new Random();
for(int i=1;i<VcodeNum+1;i++)
{
if(temp!=-1)
{
rand=new Random(i*temp*unchecked((int)DateTime.Now.Ticks));
}
int t=rand.Next(35);
if(temp!=-1&&temp==t)
{
return RndNum(VcodeNum);
}
temp=t;
VNum+=VcArray[t];
}
return VNum;
}
如果要在頁面a.ASPx生成驗證碼,則在該頁面添加一個圖片控件,假設命名為:ImageButton1,然後在page_Load事件中寫如下代碼:
ImageButton1.ImageUrl = "image.ASPx";
這樣就可以生成驗證碼了,image.aspx頁面可以隨便放在哪裡,不過要注意ImageButton1.ImageUrl 要寫對,同級可以直接寫image.aspx,上一級寫../image.ASPx,很方便吧。