您的位置:首页 > 编程语言 > C#

生成随机验证码--C#

2007-01-27 17:23 387 查看
public void MakeCheckCode(string checkCodeCookieName, int len)
{
//这儿定义你期待产生的随机字母
string[] arrLetter = new string[] {
"A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "2", "3", "4", "5", "6", "7", "8", "9"
};
//随机颜色
Color[] arrColor = new Color[] { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Green, Color.Brown, Color.DarkCyan, Color.Blue };
//随机字体
string[] arrFont = new string[] { "Arial", "Verdana" };

Random romTemp = new Random();
string strCheckCode = "";
//产生随机字符串
for (int i = 1; i <= len; i++)
{
strCheckCode = strCheckCode + arrLetter[romTemp.Next(arrLetter.Length)];
}
strCheckCode = strCheckCode.ToUpper();
//将值写入cook
HttpCookie cookTemp = new HttpCookie(checkCodeCookieName);
cookTemp.Values.Add("CheckCode", strCheckCode);
this.Context.Response.Cookies.Add(cookTemp);
int intWidth = strCheckCode.Length * 13; //计算图片需要的宽度
Bitmap bitmap1 = new Bitmap(intWidth,0x16);
//绘图
Graphics graphics1 = Graphics.FromImage(bitmap1);
graphics1.Clear(Color.White);
for (int i = 0; i < 5; i++)
{
//随机字母宽度
int intLetterWidth = romTemp.Next(bitmap1.Width);
//随机字母高度
int intLetterHeight = romTemp.Next(bitmap1.Height);
graphics1.DrawRectangle(new Pen(Color.DarkGray, 0f), intLetterWidth, intLetterHeight, 1, 1);
}
for (int i = 0; i < strCheckCode.Length; i++)
{
int num7 = romTemp.Next(arrColor.Length);
int num8 = romTemp.Next(arrFont.Length);
Font font1 = new Font(arrFont[num8], 10f, FontStyle.Bold);
Brush brush1 = new SolidBrush(arrColor[num7]);
graphics1.DrawString(strCheckCode.Substring(i, 1), font1, brush1, (float) (3 + (i * 11)), 3f);
}
graphics1.DrawRectangle(new Pen(Color.LightGray, 0f), 0, 0, bitmap1.Width - 1, bitmap1.Height - 1);
graphics1.Dispose();
System.IO.MemoryStream stream1 = new System.IO.MemoryStream();
bitmap1.Save(stream1, System.Drawing.Imaging.ImageFormat.Gif);
this.Context.Response.ClearContent();
this.Context.Response.ContentType = "image/Gif";
this.Context.Response.BinaryWrite(stream1.ToArray());
bitmap1.Dispose();
graphics1.Dispose();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: