.net 驗證碼代碼

代碼:

隨機數代碼:

private string CreateRandomCode(int codecount)
    {
        string allchar = "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,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[] allcharArray = allchar.Split(',');
        string randomCode = "";
        int temp;
        Random rand = new Random();
        for (int i = 0; i < codecount; i++)
        {
            int t = rand.Next(71);
            temp = t;
            randomCode +=allcharArray[t];
        }
        return randomCode;
    }


  干擾圖片代碼:

  private void CreateImage(string checkcode)
    {
        int iwidth = (int)(checkcode.Length * 30);
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth,50);
        Graphics g = Graphics.FromImage(image);
        Font f = new System.Drawing.Font("Arial",25,System.Drawing.FontStyle.Bold);
        Brush b = new System.Drawing.SolidBrush(Color.White);
        g.Clear(Color.Red);
        g.DrawString(checkcode,f,b,3,3);
        Pen blackpen = new Pen(Color.Blue,0);
        Random rand = new Random();
        for (int i = 0; i < 4; i++)
        {
            int y = rand.Next(image.Height);
            g.DrawLine(blackpen,0,y,image.Width,y);
        }
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
        Response.ClearContent();
        Response.ContentType = "image/Jpeg";
        Response.BinaryWrite(ms.ToArray());
        g.Dispose();
        image.Dispose();
       
    }

 

調用上面的兩個方法的page_load

 protected void Page_Load(object sender, EventArgs e)
    {
        string checkcode = CreateRandomCode(4);
        Session["checkcode"] = checkcode;
        CreateImage(checkcode);
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章