两个不错的生成图片验证码代码
推荐 图片验证码
今天在学习李天平的CodeMatic代码生成器时,看到后台登陆有一个验证码,便看看了,还是比较好用的,特地记录一下,以备他用.
用的时候,自己建立一个aspx文件,把下面的代码复制进去,记得看清楚哦,这个是连Page_Load都有的,覆盖掉原来的就可以了,然后再需要验证码的地方拖一个image服务器控件,src就选择为自己建立的那个aspx文件.你如果觉得自己处理麻烦,可以下载我这个,添加到项目里就可以了(ValidateCode.aspx.rar)
Code
private void Page_Load(object sender, System.EventArgs e)
{
string checkCode = GetRandomCode(4);
Session["CheckCode"] = checkCode;
SetPageNoCache();
CreateImage(checkCode);
}
/**//// <summary>
/// 设置页面不被缓存
/// </summary>
private void SetPageNoCache()
{
Response.Buffer = true;
Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "No-Cache");
}
private string CreateRandomCode(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(35);
if (temp == t)
{
return CreateRandomCode(codeCount);//性能问题
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
private string GetRandomCode(int CodeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string RandomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < CodeCount; i++)
{
if (temp != -1)
{
rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(33);
while (temp == t)
{
t = rand.Next(33);
}
temp = t;
RandomCode += allCharArray[t];
}
return RandomCode;
}
private void CreateImage(string checkCode)
{
int iwidth = (int)(checkCode.Length * 14);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
Graphics g = Graphics.FromImage(image);
Font f = new System.Drawing.Font("Arial ", 10);//, System.Drawing.FontStyle.Bold);
Brush b = new System.Drawing.SolidBrush(Color.Black);
Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));
//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
// g.Clear(Color.AliceBlue);//背景色
g.Clear(System.Drawing.ColorTranslator.FromHtml("#99C1CB"));//背景色
char[] ch = checkCode.ToCharArray();
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] >= '0' && ch[i] <= '9')
{
//数字用红色显示
g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);
}
else
{ //字母用黑色显示
g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
}
}
//for循环用来生成一些随机的水平线
// Pen blackPen = new Pen(Color.Black, 0);
// Random rand = new Random();
// for (int i=0;i<5;i++)
// {
// int y = rand.Next(image.Height);
// g.DrawLine(blackPen,0,y,image.Width,y);
// }
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
//history back 不重复
Response.Cache.SetNoStore();//这一句
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
private void Page_Load(object sender, System.EventArgs e)
{
string checkCode = GetRandomCode(4);
Session["CheckCode"] = checkCode;
SetPageNoCache();
CreateImage(checkCode);
}
/**//// <summary>
/// 设置页面不被缓存
/// </summary>
private void SetPageNoCache()
{
Response.Buffer = true;
Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "No-Cache");
}
private string CreateRandomCode(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(35);
if (temp == t)
{
return CreateRandomCode(codeCount);//性能问题
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
private string GetRandomCode(int CodeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,i,J,K,M,N,P,Q,R,S,T,U,W,X,Y,Z";
string[] allCharArray = allChar.Split(',');
string RandomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < CodeCount; i++)
{
if (temp != -1)
{
rand = new Random(temp * i * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(33);
while (temp == t)
{
t = rand.Next(33);
}
temp = t;
RandomCode += allCharArray[t];
}
return RandomCode;
}
private void CreateImage(string checkCode)
{
int iwidth = (int)(checkCode.Length * 14);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
Graphics g = Graphics.FromImage(image);
Font f = new System.Drawing.Font("Arial ", 10);//, System.Drawing.FontStyle.Bold);
Brush b = new System.Drawing.SolidBrush(Color.Black);
Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));
//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
// g.Clear(Color.AliceBlue);//背景色
g.Clear(System.Drawing.ColorTranslator.FromHtml("#99C1CB"));//背景色
char[] ch = checkCode.ToCharArray();
for (int i = 0; i < ch.Length; i++)
{
if (ch[i] >= '0' && ch[i] <= '9')
{
//数字用红色显示
g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);
}
else
{ //字母用黑色显示
g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
}
}
//for循环用来生成一些随机的水平线
// Pen blackPen = new Pen(Color.Black, 0);
// Random rand = new Random();
// for (int i=0;i<5;i++)
// {
// int y = rand.Next(image.Height);
// g.DrawLine(blackPen,0,y,image.Width,y);
// }
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
//history back 不重复
Response.Cache.SetNoStore();//这一句
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
想起前些日子看到Terrylee也整理的一个图片验证码(点此查看),不知道怎么用,现在突然一下恍然大悟,原来用法和上面的一样,代码贴出来,我自己修改了一点点
Code
protected void Page_Load(object sender, EventArgs e)
{
/**//**/
/**////调用函数将验证码生成图片
this.CreateCheckCodeImage(GenerateCheckCode());
}
/**//**/
/**//// <summary>
/// 产生五位的随机字符串
/// </summary>
/// <returns></returns>
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 5; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
/**//**/
/**////用于客户端校验码比较
Session["CheckCode"] = checkCode;
return checkCode;
}
/**//**/
/**//// <summary>
/// 将验证码生成图片显示
/// </summary>
/// <param name="checkCode"></param>
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image);
try
{
/**//**/
/**////生成随机生成器
Random random = new Random();
/**//**/
/**////清空图片背景色
g.Clear(Color.White);
/**//**/
/**////画图片的背景噪音线
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("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
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, brush, 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();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
protected void Page_Load(object sender, EventArgs e)
{
/**//**/
/**////调用函数将验证码生成图片
this.CreateCheckCodeImage(GenerateCheckCode());
}
/**//**/
/**//// <summary>
/// 产生五位的随机字符串
/// </summary>
/// <returns></returns>
private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 5; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
/**//**/
/**////用于客户端校验码比较
Session["CheckCode"] = checkCode;
return checkCode;
}
/**//**/
/**//// <summary>
/// 将验证码生成图片显示
/// </summary>
/// <param name="checkCode"></param>
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image);
try
{
/**//**/
/**////生成随机生成器
Random random = new Random();
/**//**/
/**////清空图片背景色
g.Clear(Color.White);
/**//**/
/**////画图片的背景噪音线
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("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
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, brush, 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();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
同样和李天平的那个用法,还有我的aspx文件下载(val.aspx.rar)