今天上網搜了搜怎麼來產生驗證碼,例子好多的,看了一篇文章,有了一個大概的瞭解
我對 .net 的類 如BitMap 還不太瞭解,只能根據別人的來做了。他是用 VB .net 來做的,俺不會 VB.net ,只能用 C# 了。
首先建立一個 Web 項目,完成後建立一個Web Form,名為 Gif.aspx
建一方法
private void createPic(string str)
{
System.Drawing.Bitmap bmp;
System.Drawing.Graphics g;
System.IO.MemoryStream ms;
// 還不明白為什麼要這樣做,一會再看看教程
int picLen=str.Length*12;
bmp=new Bitmap(picLen,20);
g=System.Drawing.Graphics.FromImage(bmp);
g.DrawString(str,(new Font("Arial",12)),(new SolidBrush(Color.Blue)),1,1);
ms=new System.IO.MemoryStream();
bmp.Save(ms,ImageFormat.Png);
Response.ClearContent();
Response.ContentType="image/png";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
bmp.Dispose();
Response.End();
}
做一個產生隨機數的方法
private string createRandomiz(int n)
{
System.Random r=new Random();
string str="0,1,2,3,4,5,6,7,8,9,q,w,e,r,t,y,u,i,o,p,a,s,d,f,g,h,j,k,l,z,x,c,v,b,n,m";
char[] a=new char[1];
a[0]=',';
string[] str1=str.Split(a);
string temp="";
for ( int i=0 ;i<n;i++)
{
temp=temp+str1[r.Next(35)].ToString();
}
return temp;
}
然後在 page_load 裡調用就行了
private void Page_Load(object sender, System.EventArgs e)
{
string num=this.createRandomiz(4); // 產生 4 個隨機數
Session["a"]=num; //這裡用 Session 來儲存
this.createPic(num);
}
在 WebForm1 裡加一個 image 的 網頁伺服器控制項 將 imageUrl 設為 gif.aspx
拖放一個 button 和一個 TextBox
在 Button 裡寫
if ( this.TextBox1.Text !=Session["a"].ToString())
{
Response.Write("error");
}
else
{
Response.Write("ok");
}
這樣就完成了,繼續看教程了