首先,新建createImage.aspx
在CreateImage.aspx.cs中,添加如下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Text;
public partial class CreateImage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// string checkCode=CreateNumCode(4);//生成四位数字验证码
string checkCode = CreateCode(4);//生成四位数字+字母验证
//string checkCode = GetString(4);//生成四位汉字验证码
Session["CheckCode"] = checkCode;
CreateImages(checkCode);
}
/*产生数字+字母验证码*/
/*算法思想:将所有数字及字母存储在字符串中,调用Random()函数随机选取子字符串数组中的一个字符,加入
指定的字符串末尾,如此反复,最终返回生成好的验证码*/
public string CreateCode(int codeLength)
{
string so = "1,2,3,4,5,6,7,8,9,0,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
string[] strArr=so.Split(',');
string code = "";
Random rand=new Random();
for (int i = 0; i < codeLength; i++)
{
code+=strArr[rand.Next(0, strArr.Length)];
}
Session["CheckCode"] = code;
return code;
}
private string CreateNumCode(int codeCount) //生成纯数字验证码
{
string allChar = "0,1,2,3,4,5,6,7,8,9";
string[] allCharArray = allChar.Split(',');//将allChar的每个由逗号分隔的元素添加到数组中
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks)); //更换随机数生成器种子避免产生相同随机数
}
int t = rand.Next(9);//返回一个小于9的非负随机数
if (temp == t) //保证连续两个生成的随机数不同
{
return CreateNumCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
Session["CheckCode"] = randomCode;
return randomCode;
}
/**/
/*
此函数在汉字编码范围内随机创建含两个元素的十六进制字节数组,每个字节数组代表一个汉字,并将
四个字节数组存储在object数组中。
参数:strlength,代表需要产生的汉字个数
*/
public static object[] CreateChiCode(int strlength)
{
//定义一个字符串数组储存汉字编码的组成元素
string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
Random rnd = new Random();
//定义一个object数组用来存放随机生成的汉字
object[] bytes = new object[strlength];
/**/
/*每循环一次产生一个含两个元素的十六进制字节数组,并将其放入bject数组中
每个汉字有四个区位码组成
区位码第1位和区位码第2位作为字节数组第一个元素
区位码第3位和区位码第4位作为字节数组第二个元素
*/
for (int i = 0; i < strlength; i++)
{
//区位码第1位
int r1 = rnd.Next(11, 14);//返回一个介于11到14的随机数
string str_r1 = rBase[r1].Trim();
//区位码第2位
rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机数发生器的种子避免产生重复值
int r2;
if (r1 == 13)
{
r2 = rnd.Next(0, 7);
}
else
{
r2 = rnd.Next(0, 16);
}
string str_r2 = rBase[r2].Trim();
//区位码第3位
rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);
int r3 = rnd.Next(10, 16);
string str_r3 = rBase[r3].Trim();
//区位码第4位
rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
int r4;
if (r3 == 10)
{
r4 = rnd.Next(1, 16);
}
else if (r3 == 15)
{
r4 = rnd.Next(0, 15);
}
else
{
r4 = rnd.Next(0, 16);
}
string str_r4 = rBase[r4].Trim();
//定义两个字节变量存储产生的随机汉字区位码
byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);
//将两个字节变量存储在字节数组中
byte[] str_r = new byte[] { byte1, byte2 };
//将产生的一个汉字的字节数组放入object数组中
bytes.SetValue(str_r, i);
}
return bytes;
}
private string GetString(int length) //生成指定位数的汉字验证码,并转换为String类型
{
object[] obj=CreateChiCode(length);
Encoding gb = Encoding.GetEncoding("gb2312");
String[] bytes= new String[length];
String code = "";
for (int i = 0; i < length; i++)
{
bytes[i] = gb.GetString((byte[])Convert.ChangeType(obj[i], typeof(byte[])));
// bytes[i] = obj[i].ToString();
code = code+bytes[i];
}
Session["CheckCode"] = code;
return code;
}
/*产生验证图片*/
public void CreateImages(string code)
{
Bitmap image = new Bitmap(120, 40);
Graphics g = Graphics.FromImage(image);
WebColorConverter ww=new WebColorConverter();
g.Clear((Color)ww.ConvertFromString("#FAE264"));
Random random = new Random();
//画图片的背景噪音线
for (int i = 0; i < 12; 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.LightGray), x1, y1, x2, y2);
}
Font font = new Font("Arial", 15, FontStyle.Bold | FontStyle.Italic);
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0,0,image.Width,image.Height),Color.Blue,Color.Gray,1.2f,true);
g.DrawString(code, font, brush, 0, 0);
//画图片的前景噪音点
for (int i = 0; i < 10; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height);
image.SetPixel(x, y, Color.White);
}
//画图片的边框线
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());
g.Dispose();image.Dispose();
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
CreateImage.aspx中不需添加任何代码
之后,新建webform1.aspx
在网页中添加如下代码:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>WebForm1
</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"/>
<meta name="CODE_LANGUAGE" Content="C#"/>
<meta name="vs_defaultClientScript" content="JavaScript"/>
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"/>
</head>
<body MS_POSITIONING="gridlayout">
<form id="Form1" method="post" runat="server">
<img src="CreateImage.aspx" align="middle" >
<BR>
</form>
</body>
</html>
对应的cs文件中不需添加任何代码,此时即可完成
看看效果吧
附加一个登陆界面应用验证码的实例:
新建login.aspx
login.aspx中
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="login">
<table cellpadding="0" cellspacing="0" border="0" style="width: 400px">
<tr>
<td>
<span>账号</span>
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<span>密码</span>
</td>
<td>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<span>验证码</span>
</td>
<td>
<asp:TextBox ID="TextBox3" runat="server" Width="120px"></asp:TextBox>
<img src="CreateImage.aspx" alt="点击刷新" id="imgValidateCode" style="width:100px; height:40px;line-height:30px;vertical-align:middle;" />
</td>
</tr>
<tr>
<td colspan="2">
<div style="margin-left: 42px">
<asp:Button ID="Button1" runat="server" οnclick="Button1_Click1" Text="登陆" />
<asp:Button ID="Button2" runat="server" οnclick="Button2_Click1" Text="重置" />
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
对应的cs文件中,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
string checkCode = this.TextBox3.Text.Trim();
//判断验证码是否为空
if (checkCode == "" || checkCode == null)
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>alert('请输入验证码!');</script>");
return;
}
else
{
//判断验证码输入是否正确
if (String.Compare(Session["CheckCode"].ToString(), checkCode, true) != 0) //compare函数可以选择是否忽略大小写
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>alert('验证码错误!');</script>");
return;
}
else if (String.Compare(Session["CheckCode"].ToString(), checkCode, true) == 0)
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "<script>alert('验证成功!');</script>");
return;
}
}
}
protected void Button2_Click1(object sender, EventArgs e)
{
this.TextBox1.Text = "";
this.TextBox3.Text = "";
this.TextBox2.Text = "";
}
}
看看效果