yulei's blog

有梦想更有要有行动,每天前进一小步,那么每年可以迈出一大步 QQ:65072096 MSN:coolsoft2001@sina.com

导航

验证码示例

验证码示例:

验证码示例

protected void Page_Load(object sender, EventArgs e)
{
BugNote.Common.CheckCode code = new BugNote.Common.CheckCode();
code.CreateCheckCodeImage(this, BugNote.Common.CheckCode.GenerateCheckCode());
}

验证码代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.UI;
using System.Drawing.Drawing2D;
using System.IO;
namespace BugNote.Common
{
///   
///   功能描述:验证码基础类
///   
public class CheckCode
{
///   
///   生成字符型验证码
///   
///   字符型验证码(四位)
public static string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;
System.Random random = new Random();
for (int i = 0; i < 4; i++)
{
number = random.Next();
if (number % 2 == 0)
code = (char)('0' + (char)(number % 10));
else
code = (char)('A' + (char)(number % 26));
checkCode += code.ToString();
}
return checkCode;
//throw   new   System.NotImplementedException();
}
///   
///   创建验证码的图片
///   by   David   2006-12-28   16:10
///   
///   
///   
public void CreateCheckCodeImage(Page containsPage, string checkCode)
{
System.Drawing.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 < 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);
}
Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0,
image.Width, image.Height),
Color.Blue, Color.DarkRed, 1.2f, true);
g.DrawString(checkCode, font, brush, 3, 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 stream = new MemoryStream();
image.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
//输出图片containsPage
containsPage.Response.Clear();
containsPage.Response.ContentType = "image/bmp";
containsPage.Response.BinaryWrite(stream.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
#region     得到验证码图片的长度
///   
///   得到验证码图片的长度
///   by   David   2006-12-28   16:35
///   
///   
///   
public static int GetImageWidth(int validateNumLength)
{
return (int)(validateNumLength * 12.5);
}
#endregion
#region   得到验证码的高度
///   
///   得到验证码的高度
///   by   David   2006-12-28   16:50
///   
///   
public static double GetImageHeight()
{
return 22.5;
}
#endregion
}
}

posted on 2008-05-16 14:22  yulei  阅读(321)  评论(0)    收藏  举报