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

ASP.NET产生随机验证码

2013-07-08 20:31 393 查看
protected void Page_Load(object sender, EventArgs e)
{
//用来保存随机字符串
string chkCode = string.Empty;

//字体的颜色
Color[] color = new Color[] {Color.Black,Color.Red,Color.Blue,Color.Green,
Color.Brown,Color.DarkBlue,Color.Gray};

//字体
string[] font = new string[]{"Times New Roman","MS Mincho","Book Antiqua",
"Gungsuh", "PMingLiU", "Impact"};

//字符串集合
char[] character = new char[] { '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' };

//Random用来产生随机数
Random rd = new Random();

for (int i = 0; i < 4;i++ )
{
chkCode += character[rd.Next(character.Length)]; //随机产生一个字母,最后组成验证码
}

//定义一副位图
Bitmap bmp = new Bitmap(100, 40); //指定大小

//创建画布,来自位图bmp
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);

//画线
for (int i = 0; i < 10;i++ )
{
int x1 = rd.Next(100); //随机产生点的位置
int y1 = rd.Next(40);
int x2 = rd.Next(100);
int y2 = rd.Next(40);
Color clr=color[rd.Next(color.Length)]; //随机产生一种线的颜色
g.DrawLine(new Pen(clr), x1, y1, x2, y2);
}

//画验证码
for (int i = 0; i < chkCode.Length;i++ )
{
string fnt = font[rd.Next(font.Length)]; //随机产生一种字体
Font ft = new Font(fnt, 18);
Color clr = color[rd.Next(color.Length)]; //随机产生一种颜色
g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), i * 20 + 8, 8);
}

//画点
for (int i = 0; i < 100;i++ )
{
int x = rd.Next(bmp.Width); //随机产生点
int y = rd.Next(bmp.Height);
Color clr = color[rd.Next(color.Length)]; //随机产生颜色
bmp.SetPixel(x, y, clr);
}

Response.Buffer = true;
Response.ExpiresAbsolute = DateTime.Now.AddMilliseconds(0);
Response.Expires = 0;
Response.CacheControl = "no-cache";
Response.AppendHeader("Pragma", "No-Cache");
MemoryStream ms = new MemoryStream(); //定义一个内存流对象
try
{
bmp.Save(ms, ImageFormat.Png); //将图像以指定的格式保存到内存流中
Response.ClearContent();
Response.ContentType = "image/png"; //设置HTTP输出流的类型
Response.BinaryWrite(ms.ToArray()); //将字节写入输出流

}
finally
{
//释放资源
bmp.Dispose();
g.Dispose();
}
}

使用时将img的src设置为产生验证码文件的路径即可。

<asp:Image ID="Image1" runat="server"
src="shengchengYZM.aspx" />

<a href="Login.aspx">看不清,换一张</a>

如果要实现点击图片也能更新验证码的话,可以在image的onclick加上onclick="this.src='shengchengYZM.aspx?a='+new Date().getMilliseconds()" 。即让每次点击都请求新的图片。

注:本文转自 http://www.jb51.net/article/9492.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: