收藏一段小.net下的驗證碼片段,以便日後參考
。
{
//先產生數字字串
字串 checkCode = this.CreateRandomCode(6);
//用會話保存
會話["CheckCode"] = checkCode;
//作圖
創建圖像(檢查程式碼);
}
私有無效CreateImage(字串檢查程式碼)
{
System.Drawing.Bitmap image = new System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 14))), 22);
圖形 g = Graphics.FromImage(image);
嘗試
{
隨機隨機 = new Random();
g.Clear(Color.AliceBlue);
for (int i = 0; i < 25; i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Comic Sans MS", 12, System.Drawing.FontStyle.Bold);
System.Drawing.Drawing2D.LinearGradientBrush畫筆 = new System.Drawing.Drawing2D.LinearGradientBrush(new 矩形(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, 字體, new SolidBrush(Color.Red), 2, 2);
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.FromArgb(random.Next()));
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1)
;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
圖像.儲存(毫秒,System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "圖片/Gif";
Response.BinaryWrite(ms.ToArray());
}
最後
{
g.Dispose();
圖像.Dispose();
}
}
公有字串 CreateRandomCode(int codeCount)
{
字串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」;
string[] allCharArray = allChar.Split(',');
字串隨機代碼 = "";
整數溫度=-1;
隨機蘭特 = new Random();
for (int i = 0; i < codeCount; i++)
{
如果(溫度!= -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(36);
if (溫度!= -1 && 溫度 == t)
{
返回 CreateRandomCode(codeCount);
}
溫度=t;
randomCode += allCharArray[t];
}
返回隨機碼;
http://www.cnblogs.com/jackyrong/archive/2006/08/25/486281.html