关于验证码整理的新版本

关于验证码整理的新版本,仅修改vcode.aspx文件,其余不变.

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;
using System.Drawing.Drawing2D;

public partial class Test_vcode : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//生成N位的验证码
//string tmp = RndNum(4);//8是可变的,一般是4位长度的验证码
//string tmp = "是可变的";//支持中文,但要求有GB字库
string tmp = GenCHCode(3);//要修改图片的宽度,一个汉字占用2个位置

//可以使用cookies或session技术来存储串,然后在主调页面中处理串比较
//HttpCookie a = new HttpCookie("CheckCode", tmp);//可变ImageV
//Response.Cookies.Add(a);

Session["CheckCode"] = tmp;//使用Session存储

#region 随机使用一种验证码显示标准


Random random = new Random();
int rd = random.Next()%3;
switch (rd)
{
case 0:
this.ValidateCode(tmp);
break;
case 1:
CreateImage(tmp);
break;
case 2:
CreateCheckCodeImage(tmp);
break;
default:
break;
}
#endregion
//多种形式的验证码
//ValidateCode(tmp);
//CreateImage(tmp);//主要使用这个方法,因为这个方法是加强的- 
// CreateCheckCodeImage(tmp);
}
#region 生成随机串
/// <summary>
/// 生成随机校验码字符串
/// </summary>
/// <returns>生成的随机校验码字符串</returns>
private string GenerateCheckCode()
{
int number;
string strCode = string.Empty;

//随机数种子
Random random = new Random();

for (int i = 0; i < 4; i++) //校验码长度为4
{
//随机的整数
number = random.Next();

//字符从0-9,A-Z中随机产生,对应的ASCII码分别为
//48-57,65-90
number = number % 36;
if (number < 10)
{
number += 48;
}
else
{
number += 55;
}

strCode += ((char)number).ToString();
}

//在Cookie中保存校验码
Response.Cookies.Add(new HttpCookie("CheckCode", strCode));
return strCode;
}

/// <summary>
/// 生成随机字串
/// </summary>
/// <param name="VcodeNum"></param>
/// <returns></returns>
private string RndNum(int VcodeNum)
{
string Vchar = "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,v,w,x,y,z";
string[] VcArray = Vchar.Split(new Char[] { ',' });
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(35);
if (temp != -1 && temp == t)
{
return RndNum(VcodeNum);
}
temp = t;
VNum += VcArray[t];
}
return VNum;
}
/**/
/// <summary>
/// '产生随机中文字符串
/// </summary>
/// <param name="num">随机出几个字符</param>
/// <returns>随机出的字符串</returns>
private string GenCHCode(int num)
{
string str = "0123456789" + //10
"abcdefghijklmnopqrstuvwxyz" + //26
"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + //26
"的一是在不了有和人这中大为上个" + //15
"国我以要他时来用们生到作地于出"+
"就分对成会可主发年动同工也能下"+
"过子说产种面而方后多定行学法所"+
"民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府称太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严";
char[] chastr = str.ToCharArray();
// string[] source ={ "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", "V", "W", "X", "Y", "Z", "#", "$", "%", "&", "@" };
string code = "";
Random rd = new Random();
int i;
for (i = 0; i < num; i++)
{
//code += source[rd.Next(0, source.Length)];
code += str.Substring(rd.Next(0, str.Length), 1);
}
return code;

}
#endregion


#region 生成图片的机制

/// <summary>
/// 黑白的简单验证码
/// </summary>
/// <param name="VNum"></param>
private void ValidateCode(string VNum)
{
Bitmap Img = null;
Graphics g = null;
MemoryStream ms = null;
//int gwidth = VNum.Length * 12;//数字,字母宽度
int gwidth = VNum.Length * 12*2;//*2表示汉字
Img = new Bitmap(gwidth, 25);
g = Graphics.FromImage(Img);
//背景颜色
g.Clear(Color.White);
//文字
Font f = new Font("Arial Black", 10);
//文字颜色
SolidBrush s = new SolidBrush(Color.Black);
g.DrawString(VNum, f, s, 3, 3);
ms = new MemoryStream();
Img.Save(ms, ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());

g.Dispose();
Img.Dispose();
Response.End();
}
/// <summary>
/// 输出不同字体和颜色的验证码
/// </summary>
/// <param name="checkCode"></param>
private void CreateImage(string checkCode)
{
//int iwidth = (int)(checkCode.Length * 15);//在数字+字母模式下
int iwidth = (int)(checkCode.Length * 15) * 2;//*2是在汉字模式下
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 25);//25图片高度
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();
//随机输出噪点 50个
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);
}
//画图片的背景噪音线 10条
for (int i = 0; i < 10; i++)
{
//噪音线起点坐标(x1,y1),终点坐标(x2,y2)
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.Silver), x1, y1, x2, y2);
}

//输出不同字体和颜色的验证码字符
for (int i = 0; i < checkCode.Length; i++)
{
int cindex = rand.Next(7);
int findex = rand.Next(5);

Font f = new System.Drawing.Font(font[findex], 12, System.Drawing.FontStyle.Bold);//修改字体大小
Brush b = new System.Drawing.SolidBrush(c[cindex]);
int ii = 4;
if ((i + 1) % 2 == 0)
{
ii = 2;
}
g.DrawString(checkCode.Substring(i, 1), f, b, 3 + (i * 12), ii);
}
//画一个边框
// g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);


//输出到浏览器
System.IO.MemoryStream ms = new System.IO.MemoryStream();

//图片变形
image = TwistImage(image, true, 6, 0);

image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
/// <summary>
/// 根据校验码输出图片
/// </summary>
/// <param name="checkCode">产生的随机校验码</param>
private void CreateCheckCodeImage(string checkCode)
{
//若校验码为空,则直接返回
if (checkCode == null || checkCode.Trim() == String.Empty)
return;
//int width = checkCode.Length * 15;//数字,字母宽度
int width = checkCode.Length * 15 * 2;//*2表示兼容汉字
//根据校验码的长度确定输出图片的长度
System.Drawing.Bitmap image = new System.Drawing.Bitmap(
(int)Math.Ceiling((decimal)(width)), 20);

//创建Graphics对象
Graphics g = Graphics.FromImage(image);

try
{
//生成随机数种子
Random random = new Random();

//清空图片背景色
g.Clear(Color.White);

//画图片的背景噪音线 10条
for (int i = 0; i < 10; i++)
{
//噪音线起点坐标(x1,y1),终点坐标(x2,y2)
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.Silver), x1, y1, x2, y2);
}

//输出图片中校验码的字体: 12号Arial,粗斜体
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.Purple,
1.2f,
true);
g.DrawString(checkCode, font, brush, 2, 2);

//画图片的前景噪音点 50个
for (int i = 0; i < 50; 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.SaddleBrown),
0,
0,
image.Width - 1,
image.Height - 1);

//创建内存流用于输出图片
using (MemoryStream ms = new MemoryStream())
{
//图片格式指定为png
image.Save(ms, ImageFormat.Png);

//清除缓冲区流中的所有输出
Response.ClearContent();

//输出流的HTTP MIME类型设置为"image/Png"
Response.ContentType = "images/Png";

//输出图片的二进制流
Response.BinaryWrite(ms.ToArray());
}
}
finally
{
//释放Bitmap对象和Graphics对象
g.Dispose();
image.Dispose();
}
}
#endregion
#region 主页面中的调用
// //判断Cookie是否为空,若为空说明浏览器禁用了Cookie
//if (Request.Cookies["CheckCode"] == null)
//{
// lblMessage.Text = "您的浏览器设置已被禁用 Cookies,您必须设置浏览器允许使用 Cookies 选项后才能使用本系统。";
// lblMessage.Visible = true;
// return;
//}

////判断输入校验码是否正确
//if (String.Compare(Request.Cookies["CheckCode"].Value, tbCheckCode.Text, true) != 0)
//{
// lblMessage.Text = "验证码错误,请输入正确的验证码。";
// lblMessage.Visible = true;
// return;
//}
#endregion
#region 图片变形
/**/
/// <summary>
/// 正弦曲线Wave扭曲图片(Edit By 51aspx.com)
/// </summary>
/// <param name="srcBmp">图片路径</param>
/// <param name="bXDir">如果扭曲则选择为True</param>
/// <param name="nMultValue">波形的幅度倍数,越大扭曲的程度越高,一般为3</param>
/// <param name="dPhase">波形的起始相位,取值区间[0-2*PI)</param>
/// <returns></returns>
public System.Drawing.Bitmap TwistImage(Bitmap srcBmp, bool bXDir, double dMultValue, double dPhase)
{
double PI2 = 3.1415926;
int destWidth = srcBmp.Width;
int destHeight = srcBmp.Height;
System.Drawing.Bitmap destBmp = new Bitmap(destWidth, destHeight);

// 将位图背景填充为白色
System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(destBmp);
graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), 0, 0, destBmp.Width, destBmp.Height);
graph.Dispose();

double dBaseAxisLen = bXDir ? (double)destBmp.Height : (double)destBmp.Width;

for (int i = 0; i < destBmp.Width; i++)
{
for (int j = 0; j < destBmp.Height; j++)
{
double dx = 0;
dx = bXDir ? (PI2 * (double)j) / dBaseAxisLen : (PI2 * (double)i) / dBaseAxisLen;
dx += dPhase;
double dy = Math.Sin(dx);

// 取得当前点的颜色
int nOldX = 0, nOldY = 0;
nOldX = bXDir ? i + (int)(dy * dMultValue) : i;
nOldY = bXDir ? j : j + (int)(dy * dMultValue);

System.Drawing.Color color = srcBmp.GetPixel(i, j);
if (nOldX >= 0 && nOldX < destBmp.Width
&& nOldY >= 0 && nOldY < destBmp.Height)
{
destBmp.SetPixel(nOldX, nOldY, color);
}
}
}

return destBmp;
}

#endregion

}

posted @ 2009-04-15 09:21  与时俱进  阅读(305)  评论(0编辑  收藏  举报
友情链接:同里老宅院民居客栈