验证码效果代码:
/*编写者:吴蒋
时间:2010-07-21
修改者:
修改内容:
*/
using System;
using System.Drawing;
using System.Text;
public partial class Inc_ValidateCode : System.Web.UI.Page
{
#region 页面事件
/// <summary>
/// 页面加载事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
this.CreateCheckCodeImage(GenerateCheckCode());
}
#endregion
#region 函数
/// <summary>
/// 随机字母和数字生成函数
/// </summary>
/// <returns>string</returns>
private string GenerateCheckCode()
{
int number;//存储随机数
char code;//字符容器
StringBuilder checkCode = new StringBuilder();//拼接字符串容器
Random random = new Random();//创建随机方法对象
for (int i = 0; i < 5; i++)//循环6次
{
number = random.Next();//获得随机数
if (number % 2 == 0)//偶数
{
code = (char)('0' + (char)(number % 10));//获得显示的字符
}
else
{
code = (char)('A' + (char)(number % 26));//获得显示的字符
}
checkCode.Append(code.ToString());//拼接字符串
}
Session["CheckCode"] = checkCode;//写入Session
Session.Timeout = 30;//过期时间
//Response.Cookies.Add(new HttpCookie("CheckCode", checkCode)); //写入Cookies
return checkCode.ToString();//返回字符串
}
/// <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();
}
}
#endregion
}