asp.net登录验证码
2008年1月4日 13:11:27 admin ASP.NET
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;
public partial class code : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string t = GenerateCheckCode();
Session["code"] = t;
Session.Timeout = 1;
CreateCheckCodeImage(t);
}
public string GenerateCheckCode()
{
int number;
char code;
string checkCode = string.Empty;//字符串的空值
Random random = new Random();
for (int i = 0; i < 4; i++)
{
number = random.Next();//非负随机数
if (number % 2 == 0)
{
code = (char)('0' + (char)(number % 10));//生成0--9的数字
}
else
{
code = (char)('a' + (char)(number % 26));//生成a--q的字母
}
checkCode += code.ToString();
}
Response.Cookies.Add(new HttpCookie("CheckCode",checkCode));//创建Cookies
return checkCode;
}
public void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == string.Empty)
return;
Bitmap image = new 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 < 2; 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.Black), x1, y1, x2, y2);
}
Font font = new Font("Arial", 12, (FontStyle.Bold));//设置字体
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Gray, Color.CornflowerBlue, 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);
MemoryStream ms = new MemoryStream();//内存缓冲区
image.Save(ms, ImageFormat.Gif);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
catch
{
g.Dispose();
image.Dispose();
}
}
}
标签:asp.net登录验证码 asp.net 登录验证码 验证码
相关文章
- asp.net登录验证 (2008-1-4 13:9:25)
- asp.net过滤危险字符 (2008-1-4 13:8:2)
- asp.net获得客户端mac地址 (2008-1-4 13:6:24)
- asp.net获取客户端ip (2008-1-4 13:5:23)
- asp.net中使用md5加密 (2008-1-4 13:3:18)
- asp.net生成html静态页 (2008-1-4 12:59:48)
发表评论