此方法可以生成自定位数的随机数,将其值存到cook中。
参数checkCodeCookieName为存储的cook名,len为生成的位数
调用此方法可以生成一个随机图片到页面上,比较用户输入的值与cook值就可起到验证的功能
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();
}
posted on
2007-01-27 17:23
qy
阅读(
643)
评论()
收藏
举报