常用的生成验证码程序,图片效果如下:
源程序如下:
复制代码 代码如下:
usingSystem;
usingSystem.IO;
usingSystem.Drawing;
usingSystem.Drawing.Imaging;
usingSystem.Text;
usingSystem.Collections;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
/**////<summary>
///
///**asp.net(C#)生成验证码**
///
///File:GenerateCheckCode.aspx.cs
///
///Author:周振兴(Zxjay飘遥)
///
///E-Mail:tda7264@163.com
///
///Date:07-04-10
///
///</summary>
publicpartialclassGenerateCheckCode:System.Web.UI.Page
...{
protectedvoidPage_Load(objectsender,EventArgse)
...{
stringchkCode=string.Empty;
//颜色列表,用于验证码、噪线、噪点
Color[]color=...{Color.Black,Color.Red,Color.Blue,Color.Green,Color.Orange,Color.Brown,Color.Brown,Color.DarkBlue};
//字体列表,用于验证码
string[]font=...{"TimesNewRoman","MSMincho","BookAntiqua","Gungsuh","PMingLiU","Impact"};
//验证码的字符集,去掉了一些容易混淆的字符
char[]character=...{'2','3','4','5','6','8','9','A','B','C','D','E','F','G','H','J','K','L','M','N','P','R','S','T','W','X','Y'};
Randomrnd=newRandom();
//生成验证码字符串
for(inti=0;i<4;i++)
...{
chkCode+=character[rnd.Next(character.Length)];
}
Bitmapbmp=newBitmap(100,40);
Graphicsg=Graphics.FromImage(bmp);
g.Clear(Color.White);
//画噪线
for(inti=0;i<10;i++)
...{
intx1=rnd.Next(100);
inty1=rnd.Next(40);
intx2=rnd.Next(100);
inty2=rnd.Next(40);
Colorclr=color[rnd.Next(color.Length)];
g.DrawLine(newPen(clr),x1,y1,x2,y2);
}
//画验证码字符串
for(inti=0;i<chkCode.Length;i++)
...{
stringfnt=font[rnd.Next(font.Length)];
Fontft=newFont(fnt,18);
Colorclr=color[rnd.Next(color.Length)];
g.DrawString(chkCode[i].ToString(),ft,newSolidBrush(clr),(float)i*20+8,(float)8);
}
//画噪点
for(inti=0;i<100;i++)
...{
intx=rnd.Next(bmp.Width);
inty=rnd.Next(bmp.Height);
Colorclr=color[rnd.Next(color.Length)];
bmp.SetPixel(x,y,clr);
}
//清除该页输出缓存,设置该页无缓存
Response.Buffer=true;
Response.ExpiresAbsolute=System.DateTime.Now.AddMilliseconds(0);
Response.Expires=0;
Response.CacheControl="no-cache";
Response.AppendHeader("Pragma","No-Cache");
//将验证码图片写入内存流,并将其以"image/Png"格式输出
MemoryStreamms=newMemoryStream();
try
...{
bmp.Save(ms,ImageFormat.Png);
Response.ClearContent();
Response.ContentType="image/Png";
Response.BinaryWrite(ms.ToArray());
}
finally
...{
//显式释放资源
bmp.Dispose();
g.Dispose();
}
}
}
使用方法如下:
新建名为GenerateCheckCode.aspx的文件,将上述代码拷贝到代码文件GenerateCheckCode.aspx.cs
在需要验证码的地方放置语句<asp:ImageID="img1"runat="server"ImageUrl="~/GenerateCheckCode.aspx"/>即可。