vs2005下彩色验证码的实现(可自由定义是否加入干扰点、验证码位数等验证码显示效果)
一、效果如下:

二、项目中添加一个类命名为(可任选)在此类中添加代码
using System;
using System.Web;
using System.IO;
using System.Drawing;

/// <summary>
/// Class1 的摘要说明
/// </summary>
public class zhangming
{
public class VerifyCode
{

验证码长度(默认5个验证码的长度)

验证码字体大小(默认10像素)

边框补(默认1像素)

是否输出燥点(默认不输出)

输出燥点的颜色(默认灰色)

自定义背景色(默认白色)

自定义随机颜色数组

自定义字体数组

自定义随机码字符串序列(使用逗号分隔)

生成校验码图片

将创建好的图片输出到页面

生成随机字符码

}
}
三、新建GetImageCode.aspx页面前台添加代码(实际前台代码无内容)
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
四、添加GetImageCode.aspx.cs后台代码
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.IO;
using System.Drawing;

public partial class Default4 : System.Web.UI.Page
{
验证码长度(默认5个验证码的长度)

验证码字体大小(默认10像素)

边框补(默认1像素)

是否输出燥点(默认输出)

输出燥点的颜色(默认灰色)

自定义背景色(默认白色)

自定义随机颜色数组

自定义字体数组

自定义随机码字符串序列(使用逗号分隔)

protected void Page_Load(object sender, EventArgs e)
{
zhangming.VerifyCode v = new zhangming.VerifyCode();

v.Length = this.length;

v.FontSize = this.fontSize;

v.Chaos = this.chaos;

v.BackgroundColor = this.backgroundColor;

v.ChaosColor = this.chaosColor;

v.CodeSerial = this.codeSerial;

v.Colors = this.colors;

v.Fonts = this.fonts;

v.Padding = this.padding;

string code = v.CreateVerifyCode(); //取随机码

v.CreateImageOnPage(code, this.Context); // 输出图片

//Session["CheckCode"] = code.ToLower(); // 使用Session["CheckCode"]取验证码的值
Response.Cookies.Add(new HttpCookie("CheckCode", code.ToLower()));// 使用Cookies取验证码的值

}
}
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Image id="Image1" runat="server" ImageUrl="GetImageCode.aspx"></asp:Image>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
Text="Button" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label></div>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Session["CheckCode"] = "";
Response.Cookies.Add(new HttpCookie("CheckCode", ""));
}
}
protected void Button1_Click(object sender, EventArgs e)
{

if (Request.Cookies["CheckCode"] == null)
{
Label1.Text = "您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";
Label1.Visible = true;
return;
}

if (String.Compare(Request.Cookies["CheckCode"].Value, TextBox1.Text.ToString().Trim(), true) != 0)
{
Label1.Text = "验证码错误,请输入正确的验证码。";
Label1.Visible = true;
return;
}
else
{
Label1.Text = "验证码OK。";
Label1.Visible = true;
}



}

二、项目中添加一个类命名为(可任选)在此类中添加代码







































三、新建GetImageCode.aspx页面前台添加代码(实际前台代码无内容)







四、添加GetImageCode.aspx.cs后台代码


































































五、验证码的使用(在Test.aspx页面加入<asp:Image id="Image1" runat="server" ImageUrl="~/GetVerifyCode.aspx"></asp:Image>)即实现验证码











六、Test.aspx.cs后台代码

































