收藏一段小的.net下的验证码片段،以供以后参考
.
{
//先产生数字串
سلسلة checkCode = this.CreateRandomCode(6);
//الجلسة
جلسة ["CheckCode"] = checkCode؛
//作图
CreateImage(checkCode);
}
إنشاء صورة باطلة خاصة (رمز التحقق من السلسلة)
{
System.Drawing.Bitmap image = new System.Drawing.Bitmap(Convert.ToInt32(Math.Ceiling((decimal)(checkCode.Length * 14))), 22);
الرسومات ز = Graphics.FromImage(image);
يحاول
{
عشوائي عشوائي = عشوائي جديد ()؛
g.Clear(Color.AliceBlue);
لـ (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 Brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, Font, new SolidBrush(Color.Red), 2, 2);
لـ (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();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
أخيراً
{
g.Dispose();
image.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؛
راند عشوائي = جديد عشوائي ()؛
لـ (int i = 0; i <codeCount; i++)
{
إذا (درجة الحرارة ! = -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(36);
إذا (درجة الحرارة != -1 && درجة الحرارة == ر)
{
إرجاع CreateRandomCode(codeCount);
}
درجة الحرارة = ر؛
RandomCode += allCharArray[t];
}
إرجاع رمز عشوائي؛
}
http://www.cnblogs.com/jackyrong/archive/2006/08/25/486281.html