private string GenerateCheckCode()
{
int number;
string strCode = string.Empty;
//随机种子
//Random random = new Random();
//for (int i = 0; i < 4; i++) //验证码长度为4
//{
// //随机整数
// number = random.Next();
// //字符从0-9,A-Z中产生,对应的ASCII码为48-57,65-90
// number = number % 36;
// if (number < 10)
// {
// number += 48;
// }
// else
// {
// number += 55;
// }
// strCode += ((char)number).ToString();
//}
//产生随机字符串
strCode = GenCode(4);
//将字符串保存在Cookies
Response.Cookies.Add(new HttpCookie("gst_checkCode", strCode));
return strCode;
}
private string GenCode(int num)
{
string[] source ={"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 code = "";
Random rd = new Random();
for (int i = 0; i < num; i++)
{
code += source[rd.Next(0, source.Length)];
}
return code;
}
//生成图片
private void CreateCheckCodeImage(string checkCode)
{
//若检验码为空,则直接返回
if (checkCode == null || checkCode.Trim() == string.Empty)
return;
//根据验证码长度确定输出图片的长度
System.Drawing.Bitmap image = new Bitmap((int)Math.Ceiling(float.Parse((checkCode.Length * 15).ToString())), 20);
//创建Graphics对象
System.Drawing.Graphics g = Graphics.FromImage(image);
//生成随机数种子
Random random = new Random();
//清除图片背景颜色
g.Clear(Color.White);
//画背景图片的噪音线10条
for (int i = 0; i < 6; i++)
{
//噪音线起点坐标(x1,y1),终点坐标(x2,y2)
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);
}
//输出图片中校验码的字体:12号Arial,粗斜体
Font font = new Font("Arial", 12, FontStyle.Bold);
//线性渐变画刷
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Width), Color.Blue, Color.Purple, 1.2f, true);
g.DrawString(checkCode, font, brush, 2, 2);
//画图片的前景噪点50个
for (int i = 0; i < 50; 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.SaddleBrown), 0, 0, image.Width - 1, image.Height - 1);
//创建内存流用于输出图片
System.IO.MemoryStream ms = new System.IO.MemoryStream();
//图片格式指定为png
image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
//清除缓冲区流中的所有输出
Response.ClearContent();
//输出流的Http Mime类型设置为"image/Png"
Response.ContentType = "image/Png";
//输出图片的二进制流
Response.BinaryWrite(ms.ToArray());
//释放Bitmap和Graphics对象
g.Dispose();
image.Dispose();
}