先看三个效果图:
以上是我今天自己根据资料学习所写的验证码截图,可以直接使用,Demo还是放在资源里面,方便大家直接拿过来使用........不足的地方希望多多指点.........
首先,验证码的实现原理:在服务器端,用编程语言生成一个随机数,并保存在内存中,然后将随机数写入设计好的图片中,发送给浏览器,并以图片形式显示给最终用户.
下面看看我的实现代码:
★★★纯数字的验证码★★★
1.MumberValidate.aspx显示页面
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MumberValidate.aspx.cs" Inherits="_Default" %>
<!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>
<script type="text/javascript" language="javascript">
function changeCode(){
var imgCode=document.getElementById("imgCode");
imgCode.src="UserValidator/MumberCheckCode.aspx?"+new Date().getTime();
}
</script>
<style type="text/css">
body
{
font-size: 12px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div align="center">
<img id="imgCode" alt="看不清楚?请点击我" οnclick="this.src=this.src+'?'" src="UserValidator/MumberCheckCode.aspx"
style="width: 73px; height: 22px; vertical-align: middle;" />
<a href="javascript:changeCode();">看不清楚?换一张</a>
</div>
</form>
</body>
</html>
2.调用生成验证码的页面MumberCheckCode.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.Drawing;
using System.IO;
using System.Drawing.Imaging;
public partial class checkCode : System.Web.UI.Page
{
#region Attribute
//checked和unchecked操作符用于整型算术运算时控制当前环境中的溢出检查
//DateTime.Now.Ticks获取表示此实例的日期和时间的计时周期数
#endregion
protected void Page_Load(object sender, EventArgs e)
{
CheckCodes(RandNum(4));
}
/// <summary>
/// 生成随机数,纯数字
/// </summary>
/// <param name="VcodeNum">生成数字的个数</param>
/// <returns></returns>
private string RandNum(int VcodeNum)
{
string Vchar = "0,1,2,3,4,5,6,7,8,9";
//分割
string[] VcArray = Vchar.Split(',');
string VNum = "";//保存生成的验证码
int temp = -1;//记录上次随机数值,尽量避免生成几个一样的随机数
//采用一个简单的算法以保证生成随机数不同
Random rand = new Random();
for (int i = 1; i < VcodeNum + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}
int t = rand.Next(VcArray.Length);
if (temp != -1 && temp == t)
{
return RandNum(VcodeNum);
}
temp = t;
VNum += VcArray[t];
}
Session["CheckCode"]=VNum;
return VNum;
}
/// <summary>
/// 生成验证图片
/// </summary>
/// <param name="checkCode">验证字符</param>
private void CheckCodes(string checkCode)
{
int iwidth = (int)(checkCode.Length * 13);
//封装GDI+位图,此位图由图形图像及其属性的像素数据 组成
Bitmap image = new Bitmap(iwidth, 23);
//封装一个CDI+绘图图面
Graphics g = Graphics.FromImage(image);
//清除整个绘图面并以指定背景色填充
g.Clear(Color.White);
//定义颜色
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
//定义字体
string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
//随机数
Random rand = new Random();
//随机输出噪点
for (int i = 0; i < 50; i++)
{
int x = rand.Next(image.Width);
int y = rand.Next(image.Height);
//绘制由坐标对,宽度和高度指定的矩形
g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
}
//输出不同字体和颜色的验证码字符
for (int i = 0; i < checkCode.Length; i++)
{
int cindex = rand.Next(c.Length);
int findex = rand.Next(font.Length);
//字体
Font f = new Font(font[findex], 10, FontStyle.Bold);
//填充图形形状
Brush b = new SolidBrush(c[cindex]);
int j = 4;
if ((i + 1) % 2 == 0)
{
j = 2;
}
//在指定的矩形绘制指定的文本字符串
g.DrawString(checkCode.Substring(i, 1), f, b, 3 + (i * 12), j);
}
//画一个边框
g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);
//输出到浏览器
MemoryStream ms = new MemoryStream();
image.Save(ms, ImageFormat.Jpeg);
//封装有关个别HTTP请求的所有HTTP特定的信息
Response.ClearContent();//-->清除所有缓冲区流中的所有内容输出
//设置输出流的类型
Response.ContentType = "image/Jpeg";
//将一个二进制字符串写入HTTP输出流
Response.BinaryWrite(ms.ToArray());
//释放
g.Dispose();
image.Dispose();
}
}
★★★数字与字母的验证码★★★
1.NumberAndLetter.aspx显示页面-同上面的显示页面相同,只是图片的连接不同,改一些就可以了
2.NumAndLetCheckCode.aspx.cs调用绘制验证码的页面
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging; //添加引用
using System.Drawing.Drawing2D;
public partial class UserValidator_NumAndLetCheckCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreateCheckCodeImage(GenerateCheckCode());
}
/// <summary>
/// 生成随机数
/// </summary>
/// <returns></returns>
private string GenerateCheckCode()
{
//数字
int number;
//字母
char code;
//保存产生的验证码字符串
string checkCode = string.Empty;
//生成随机生成器
Random rand = new Random();
for (int i = 0; i < 4; i++)
{
number = rand.Next();
//偶数位数字奇数位字母
if (number % 2 == 0)
{
//罗列数字
code = (char)('0' + (char)(number % 10));
}
else
{
//罗列字母
code = (char)('A' + (char)(number % 26));
}
checkCode += code.ToString();
}
//存入Cookies中
Response.Cookies.Add(new HttpCookie("CheckCode",checkCode));
//返回产生的验证码
return checkCode;
}
/// <summary>
/// 绘制数字和字母的验证码
/// </summary>
/// <param name="checkCode"></param>
private void CreateCheckCodeImage(string checkCode)
{
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
//封装GDI+位图
Bitmap image = new Bitmap((int)Math.Ceiling(checkCode.Length*12.25),22);
//封装一个GDI+绘图图面
Graphics g = Graphics.FromImage(image);
try
{
//生成随机生成器
Random rand = new Random();
//清空图片背景色,并以白色填充
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 2; i++)
{
int x1 = rand.Next(image.Width);
int x2 = rand.Next(image.Width);
int y1 = rand.Next(image.Height);
int y2 = rand.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.Blue,Color.DarkRed,1.2f,true);
g.DrawString(checkCode,font,brush,2,2);
//画图片的前景噪点
for (int i = 0; i < 100; i++)
{
int x = rand.Next(image.Width);
int y = rand.Next(image.Height);
image.SetPixel(x,y,Color.FromArgb(rand.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";
//将一个二进制字符串写入HTTP输出流
Response.BinaryWrite(ms.ToArray());
}
catch
{
//释放所占的系统资源
g.Dispose();
image.Dispose();
}
}
}
★★★中文验证码验证码★★★
中文验证码:绘制汉字验证码主要通过生成的汉字区位码将其转换成汉字.区位码是汉字一一对应的编码,用4位数字表示,前两位从01到94称为区码,后两位从01到94称为位码,一个汉字的前一半是ASCII码位"160+区码"的字符,后一半是ASCII码位"160+位码"的字符.例如,"房"的区位码是2331,表示的是区码23,位码31,它是由ASCII码位"160+23=183"和"160+31=191"的两个字符组成.绘制汉字验证码中生成的汉字的汉字区位码是以十六进制进行组合的,因此,程序中定义由16个字符组成的数组,以便能够生成随机字符,组成一个十六进制数据.
1.ChineseCodeValidator.aspx显示页面-同上面的显示页面相同,改变图片连接即可
2.ChineseCheckCode.aspx.cs调用绘制验证码的页面
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Text; //添加引用
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging; //添加引用
public partial class UserValidator_ChineseCheckCode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GraphicsImage(4); //调用方法生成四位汉字验证码
}
/// <summary>
/// 生成汉字区位码
/// </summary>
/// <param name="strlength"></param>
/// <returns></returns>
private object[] CreateString(int strlength)
{
//定义一个数组存储汉字编码的组成元素
string[] str = new string[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
Random ran = new Random(); //定义一个随机数对象
object[] bytes = new object[strlength];
for (int i = 0; i < strlength; i++)
{
//获取区位码第一位
int ran1 = ran.Next(11, 14);
string str1 = str[ran1].Trim();
//获取区位码第二位并防止数据重复
ran = new Random(ran1 * unchecked((int)DateTime.Now.Ticks) + i);
int ran2;
if (ran1 == 13)
{
ran2 = ran.Next(0, 7);
}
else
{
ran2 = ran.Next(0, 16);
}
string str2 = str[ran2].Trim();
//获取区位码第三位
ran = new Random(ran2 * unchecked((int)DateTime.Now.Ticks) + i);
int ran3 = ran.Next(10, 16);
string str3 = str[ran3].Trim();
//获取区位码第四位
ran = new Random(ran3 * unchecked((int)DateTime.Now.Ticks) + i);
int ran4;
if (ran3 == 10)
{
ran4 = ran.Next(1, 16);
}
else if (ran3 == 15)
{
ran4 = ran.Next(0, 15);
}
else
{
ran4 = ran.Next(0, 16);
}
string str4 = str[ran4].Trim();
//定义字节变量存储产生的随机汉字区位码
//区码
byte byte1 = Convert.ToByte(str1 + str2, 16);
//位码
byte byte2 = Convert.ToByte(str3 + str4, 16);
byte[] stradd = new byte[] { byte1, byte2 };
//将产生的汉字字节放入数组
bytes.SetValue(stradd, i);
}
return bytes;
}
/// <summary>
/// 将生成的汉字区位码转化成汉字
/// </summary>
/// <param name="length"></param>
/// <returns></returns>
private string GetString(int length)
{
//字符编码
Encoding gb = Encoding.GetEncoding("gb2312");
object[] bytes = CreateString(length);
//根据汉字字节解码出中文汉字
string str1 = gb.GetString((byte[])Convert.ChangeType(bytes[0], typeof(byte[])));
string str2 = gb.GetString((byte[])Convert.ChangeType(bytes[1], typeof(byte[])));
string str3 = gb.GetString((byte[])Convert.ChangeType(bytes[2], typeof(byte[])));
string str4 = gb.GetString((byte[])Convert.ChangeType(bytes[3], typeof(byte[])));
string str = str1 + str2 + str3 + str4;
Response.Cookies.Add(new HttpCookie("CheckCode", str));
return str;
}
/// <summary>
/// 绘制成验证码
/// </summary>
/// <param name="length"></param>
private void GraphicsImage(int length)
{
Bitmap image = new Bitmap((int)Math.Ceiling((GetString(length).Length * 22.5)), 22);
Graphics g = Graphics.FromImage(image); //创建画布
try
{
//生成随机生成器
Random random = new Random();
//清空图片背景色
g.Clear(Color.White);
//画图片的背景噪音线
for (int i = 0; i < 1; 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("Couriew New", 12, System.Drawing.FontStyle.Bold);
//使用线性渐变封装Brush
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
//绘制指定的字符串
g.DrawString(GetString(length), 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 (Exception ms)
{
Response.Write(ms.Message);
}
}
}