當前位置:名人名言大全網 - 短信平臺 - 怎樣做壹個C#的登陸驗證碼?

怎樣做壹個C#的登陸驗證碼?

protected void Page_Load(object sender, EventArgs e)

{

string checkCode = CreateRandomCode(4);

Session["CheckCode"] = checkCode;

CreateImage(checkCode);

}

private string CreateRandomCode(int codeCount)

{

// 函數功能:產生數字和字符混合的隨機字符串

string allChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

char[] allCharArray = allChar.ToCharArray();

string randomCode = "";

Random rand = new Random();

for (int i = 0; i < codeCount; i++)

{

int r=rand.Next(61);

randomCode+=allCharArray.GetValue(r);

}

return randomCode;

}

private void CreateImage(string checkCode)

{

// 生成圖象驗證碼函數

int iwidth = (int)(checkCode.Length * 11.5);

System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);

Graphics g = Graphics.FromImage(image);

Font f = new System.Drawing.Font("Arial", 10, System.Drawing.FontStyle.Bold);

Brush b = new System.Drawing.SolidBrush(Color.Azure);//字母白色

//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);

g.Clear(Color.Brown);//背景灰色

g.DrawString(checkCode, f, b, 3, 3);

Pen blackPen = new Pen(Color.Black, 0);

Random rand = new Random();

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();

}

網上找的,感謝原作者