RndCode.cs
using System;
using System.Data;
using System.Configuration;
using System.Linq;
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.Xml.Linq;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
/// <summary>
///RndCode 的摘要说明
/// 验证码类
/// </summary>
public class RndCode
{
public RndCode()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 该方法是将生成的随机数写入图像文件
/// </summary>
/// <param name="validata">一个随机数</param>
private void CreateCheckCodeImge(string validata)
{
//若校验码为空,则直接返回
if (validata == null || validata.Trim() == String.Empty)
{
return;
}
//验证码存储在Session中,供验证
System.Web.HttpContext.Current.Session.Add("ValidateCode", validata);
Bitmap img = null;
Graphics g = null;
MemoryStream ms = null;
Random rand = new Random();
//验证码颜色集合
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
//验证码字体集合
String[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
//定义图像的大小,生成图像的实例
img = new Bitmap((int)Math.Ceiling(Convert.ToDecimal(validata.Length * 18)), 32);
//从Img对象生成新的Graphics对象
g = Graphics.FromImage(img);
//背景设为白色
g.Clear(Color.White);
//在随机位置画背景点
for (int i = 0; i < 100; i++)
{
int x = rand.Next(img.Width);
int y = rand.Next(img.Height);
g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
}
//验证码绘制在g中
for (int i = 0; i < validata.Length; i++)
{
int cindex = rand.Next(7);//随机颜色索引值
int findex = rand.Next(5);//随机字体索引值
Font f = new Font(fonts[findex], 13, FontStyle.Bold);//字体
Brush b = new SolidBrush(c[cindex]);//颜色
int ii = 4;
if ((i + 1) % 2 == 0)//控制验证码不在同一高度
{
ii = 2;
}
g.DrawString(validata.Substring(i, 1), f, b, 3 + (i * 12), ii);//绘制一个验证字符
}
ms = new MemoryStream();//生成内存流对象
img.Save(ms, ImageFormat.Jpeg);//将此图像以Png图像文件的格式保存到流中
//清除缓冲区流中的所有输出
System.Web.HttpContext.Current.Response.ClearContent();
//输出流的HHT MIME类型设置为"image/png"
System.Web.HttpContext.Current.Response.ContentType = "image/Jpeg";
//输出的图片的二进制流
System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray());
System.Web.HttpContext.Current.Response.End();
//回收资源
g.Dispose();
img.Dispose();
ms.Dispose();
}
/// <summary>
/// 纯数字验证码类
/// </summary>
#region
public class SingleNumeric
{
//方法一:
private string getRandomint(int codeCount)
{
Random rand = new Random();
string min = "";
string max = "";
for (int i = 0; i < codeCount; i++)
{
min += "1";
max += "9";
}
return (rand.Next(Convert.ToInt32(min), Convert.ToInt32(max)).ToString());
}
//方法二:
private string createRandomCode(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9";
string[] allCharArray = allChar.Split(',');
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);
if (temp == t)
{
return createRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
public void MakeImg()
{
//new RndCode().CreateCheckCodeImge(getRandomint(4));
new RndCode().CreateCheckCodeImge(createRandomCode(4));
}
}
#endregion
/// <summary>
/// 数字+字母验证码类
/// </summary>
#region
public class NumericAndWord
{
private string createRandomCode(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,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[] allCharArray = allChar.Split(',');
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(61);
if (temp == t)
{
return createRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray[t];
}
return randomCode;
}
public void MakeImg()
{
new RndCode().CreateCheckCodeImge(createRandomCode(4));
}
}
#endregion
/// <summary>
/// 中文汉字验证码类
/// </summary>
#region
public class CnCode
{
/**/
/*
此函数在汉字编码范围内随机创建含两个元素的十六进制字节数组,每个字节数组代表一个汉字,并将
四个字节数组存储在object数组中。
参数:strlength,代表需要产生的汉字个数
*/
private object[] CreateRegionCode(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);
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;
}
public void MakeImg()
{
System.Text.Encoding gb = System.Text.Encoding.GetEncoding("gb2312");
object[] bytes = CreateRegionCode(4);
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 checkCode = str1 + str2 + str3 + str4;
new RndCode().CreateCheckCodeImge(checkCode);
}
}
#endregion
}
YanZhengMa.aspx.cs
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
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.Xml.Linq;
public partial class Public_YanZhengMa : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//纯数字
new RndCode.SingleNumeric().MakeImg();
//数字+字母验证码
//new RndCode.NumericAndWord().MakeImg();
//中文汉字验证码
//new RndCode.CnCode().MakeImg();
}
}
前台引用:
<asp:Image ID="Vcode" Height="32px" runat="server" ImageUrl="~/Public/YanZhengMa.aspx" />
HttpHandler实现生成图片验证码:
ValidateImageHandler.ashx:
<%@ WebHandler Language="C#" Class="ValidateImageHandler" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
/// <summary>
/// HttpHandler实现生成图片验证码
/// </summary>
public class ValidateImageHandler : IHttpHandler,IRequiresSessionState
{
int intLength = 4;//长度
string strIdentity = "Identify";//随机字串存储键值,以便存储到Session中
/// <summary>
/// 默认构造函数
/// </summary>
public ValidateImageHandler()
{
}
/// <summary>
/// 生成验证图片核心代码
/// </summary>
/// <param name="context"></param>
public void ProcessRequest (HttpContext context)
{
//设置输出流图片格式
context.Response.ContentType = "image/gif";
Bitmap b = new Bitmap(80, 32);
Graphics g = Graphics.FromImage(b);
g.FillRectangle(new SolidBrush(Color.White), 0, 0, 80, 32);
Font font = new Font(FontFamily.GenericSansSerif, 13, FontStyle.Bold, GraphicsUnit.Pixel);
Random rand = new Random();
//合法随机显示字符列表
string strLetters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder s = new StringBuilder();
//将随机生成的字符串绘制到图片上
for (int i = 0; i < intLength; i++)
{
s.Append(strLetters.Substring(rand.Next(0, strLetters.Length - 1), 1));
g.DrawString(s[s.Length - 1].ToString(), font, new SolidBrush(Color.Red), i * 18, rand.Next(0, 15));
}
//生成干扰线条
Pen pen = new Pen(new SolidBrush(Color.Black), 2);
for (int i = 0; i < 10; i++)
{
g.DrawLine(pen, new Point(rand.Next(0, 199), rand.Next(0, 59)), new Point(rand.Next(0, 199), rand.Next(0, 59)));
}
b.Save(context.Response.OutputStream, ImageFormat.Gif);
context.Session[strIdentity] = s.ToString();//先保存在Session中,验证与用户输入是否一致
context.Response.End();
}
/// <summary>
/// 表示此类实例是否可以被多个请求共用(重用可以提高性能)
/// </summary>
public bool IsReusable
{
get
{
return true;
}
}
}
前台引用:
<asp:Image ID="Vcode" Height="32px" runat="server" ImageUrl="ValidateImageHandler.ashx" />