首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

有人能给个验证码的例证吗?最好是5位的

2011-12-26 
有人能给个验证码的例子吗?最好是5位的.有人有现成的吗?要下班了,很着急!谢谢了![解决办法]建CheckCode.as

有人能给个验证码的例子吗?最好是5位的.
有人有现成的吗?要下班了,很着急!谢谢了!

[解决办法]
建CheckCode.aspx里加入方法

#region 生成随机数

private string GenerateCheckCode()
{
int number;
char code;
string checkCode = String.Empty;

System.Random random = new Random();

for(int i=0; i <5; i++)
{
number = random.Next();

if(number % 2 == 0)
code = (char)( '0 ' + (char)(number % 10));
else
code = (char)( 'A ' + (char)(number % 26));

checkCode += code.ToString();
}

Response.Cookies.Add(new HttpCookie( "CheckCode ", checkCode));

return checkCode;
}

#endregion 生成随机数

#region 随机画图

private void CreateCheckCodeImage(string checkCode)
{
if(checkCode == null || checkCode.Trim() == String.Empty)
return;

System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
Graphics g = Graphics.FromImage(image);

try
{
//生成随机生成器
Random random = new Random();

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

//画图片的背景噪音线
for(int i=0; i <25; 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.Silver), x1, y1, x2, y2);
}

Font font = new System.Drawing.Font( "Arial ", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.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 = 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);

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());
}
finally
{
g.Dispose();
image.Dispose();
}
}

#endregion 随机画图

然后在PageLoad里面调用一下CreateCheckCodeImage(GenerateCheckCode())就可以了
[解决办法]
using System;
using System.Data;
using System.Configuration;
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;

/// <summary>
/// randomCode 的摘要说明
/// </summary>
public class randomCode
{
public randomCode()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
public string RandomNum(int n) //
{
string strchar = "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,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 = strchar.Split( ', ');
string VNum = " "; //


int temp = -1; //记录上次随机数值,尽量避免产生几个一样的随机数
//采用一个简单的算法以保证生成随机数的不同
Random rand = new Random();
for (int i = 1; i < n + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}
int t = rand.Next(61);
if (temp != -1 && temp == t)
{
return RandomNum(n);
}
temp = t;
VNum += VcArray[t];
}
return VNum;//返回生成的随机数
}
}
[解决办法]
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.ComponentModel;
using System.Web;
using System.Web.UI;

namespace Components
{
/// <summary>
/// CreateValidateCode 生成随机验证码
/// </summary>
public class CreateValidateCode
{
public CreateValidateCode()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

private int intCodeLen = 5;//验证码长;
private int intFineness = 95;//图片清晰度;
private int intImgWidth = 52;//图片宽度
private int intImgHeight = 22;//图片高度
private string strFontName = "Verdana "; //字体名称
private int intFontSize = 11;//字体大小
//private string strFontStyle = "3 ";//字体样式
private int intPosX = 1;//绘制起始坐标 X
private int intPosY = 1;//绘制起始坐标 Y

/// <summary>
///随机生成验证码,验证码为 : A - Z 的英文字母
/// </summary>
public string ValidateCodeString()
{
string validateCode= " ";

//随机数对象
Random random=new Random();

for(int i=0;i <this.intCodeLen;i++)
{
//26 :A - Z
//int n = random.Next(26);
int n = random.Next(10);
//将数字转换成大写字母
//validateCode+=(char)(n+65);
validateCode+=n.ToString();
}

return validateCode;
}

/// <summary>
///为图片设置干扰点
/// </summary>
/// <param name= "bitmap "> 位图图像 </param>
public void DisturbBitmap(Bitmap bitmap)
{
//通过随机数生成
Random random=new Random();

for(int i=0; i <bitmap.Width; i++)
{
for(int j=0; j <bitmap.Height; j++)
{
if(random.Next(100) <=this.intFineness)
bitmap.SetPixel(i,j,Color.White);
}
}
}

/// <summary>
///绘制验证码图片
/// </summary>
/// <param name= "bitname "> 位图图像 </param>
/// <param name= "validateCode "> 所要绘制的验证码 </param>
public void DrawValidateCode(Bitmap bitmap, string validateCode)
{
//获取绘制器对象
Graphics g=Graphics.FromImage(bitmap);

//设置字体
Font font=new Font(this.strFontName,this.intFontSize,FontStyle.Bold);
//(FontStyle)(Enum.Parse(typeof(FontStyle),this.strFontStyle,false)));

//绘制验证码图像
g.DrawString(validateCode,font,Brushes.Black,this.intPosX,this.intPosY);
}
/// <summary>
/// 生成验证图片,以便输出
/// </summary>
/// <param name= "validateCode "> 随机验证码 </param>
/// <param name= "page "> Page对像 </param>
public void CreateImage(string validateCode,Page page)
{

//生成BITMAP图片
Bitmap bitmap = new Bitmap(this.intImgWidth,this.intImgHeight);


//绘制图片干扰
this.DisturbBitmap(bitmap);

//绘制验证码图像
this.DrawValidateCode(bitmap,validateCode);

// 保存验证码图像,等待输出
bitmap.Save(page.Response.OutputStream,ImageFormat.Gif);
}
}
}
[解决办法]
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.Drawing.Imaging;
using System.IO;

/// <summary>
/// CodeLen : 验证码字符位数
/// Fineness : 图片清晰度,0-100
/// ImgWidth : 图片宽度 16-480
/// ImgHeight : 图片高度 16-320
/// FontFamily : 字体名称
/// FontSize : 字体大小 8-72
/// FontStyle : 字体样式 1 粗体 2 斜体 3 粗斜体
/// PosX : 验证码绘制起始坐标 X
/// PosY : 验证码绘制起始坐标 Y
///
/// 结果:Session[ "ImageCode "]
/// </summary>
public partial class Service_ImageCode : System.Web.UI.Page
{
// 验证码长度
private int codeLen = 5;
// 图片清晰度
private int fineness = 90;
// 图片宽度
private int imgWidth = 85;
// 图片高度
private int imgHeight = 20;
// 字体家族名称
private string fontFamily = "Arial ";
// 字体大小
private int fontSize = 14;
// 字体样式
private int fontStyle = 2;
// 绘制起始坐标 X
private int posX = 3;
// 绘制起始坐标 Y
private int posY = 0;

protected void Page_Load(object sender, EventArgs e)
{
#region 读取 Request 传递参数
// 获取代码长度设置
if (Request[ "CodeLen "] != null)
{
try
{
codeLen = Int32.Parse(Request[ "CodeLen "]);
// 规定验证码长度
if (codeLen < 4 || codeLen > 16)
throw new System.Exception( "验证码长度必须在4到16之间 ");
}
catch (System.Exception error)
{
throw error;
}
}

// 获取图片清晰度设置
if (Request[ "Fineness "] != null)
{
try
{
fineness = Int32.Parse(Request[ "Fineness "]);
// 验证清晰度
if (fineness < 0 || fineness > 100)
throw new System.Exception( "图片清晰度必须在0到100之间 ");
}
catch (System.Exception error)
{
throw error;
}
}

// 获取图片宽度
if (Request[ "ImgWidth "] != null)
{
try
{
imgWidth = Int32.Parse(Request[ "ImgWidth "]);
if (imgWidth < 16 || imgWidth > 480)
throw new System.Exception( "图片宽度必须在16到480之间 ");
}
catch (System.Exception error)
{
throw error;
}
}

// 获取图片高度
if (Request[ "ImgHeight "] != null)
{
try
{
imgWidth = Int32.Parse(Request[ "ImgHeight "]);
if (imgWidth < 16 || imgWidth > 320)
throw new System.Exception( "图片高度必须在16到320之间 ");
}
catch (System.Exception error)


{
throw error;
}
}

// 获取验证码字体家族名称
if (Request[ "FontFamily "] != null)
{
fontFamily = Request[ "FontFamily "];
}

// 获取验证码字体大小
if (Request[ "FontSize "] != null)
{
try
{
fontSize = Int32.Parse(Request[ "FontSize "]);
if (fontSize < 8 || fontSize > 72)
throw new System.Exception( "字体大小必须在8到72之间 ");
}
catch (System.Exception error)
{
throw error;
}
}

// 获取字体样式
if (Request[ "FontStyle "] != null)
{
try
{
fontStyle = Int32.Parse(Request[ "FontStyle "]);
}
catch (System.Exception error)
{
throw error;
}
}

// 验证码绘制起始位置 X
if (Request[ "PosX "] != null)
{
try
{
posX = Int32.Parse(Request[ "PosX "]);
}
catch (System.Exception error)
{
throw error;
}
}

// 验证码绘制起始位置 Y
if (Request[ "PosY "] != null)
{
try
{
posY = Int32.Parse(Request[ "PosY "]);
}
catch (System.Exception error)
{
throw error;
}
}
#endregion

string validateCode = this.createValidateCode();

// 生成BITMAP图像
Bitmap bitmap = new Bitmap(imgWidth, imgHeight);

// 给图像设置干扰
this.disturbBitmap(bitmap);

// 绘制验证码图像
this.drawValidateCode(bitmap, validateCode);

// 保存验证码图像,等待输出
bitmap.Save(Response.OutputStream, ImageFormat.Gif);
}

#region 随机生成验证码并生成Session,返回验证码字符
private string createValidateCode()
{
string result = " ";
string include = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
Random random = new Random();
for (int i = 0; i < this.codeLen; i++)
{
result += include[random.Next(0, 35)].ToString();
}
//生成Session[ "ImageCode "]
Session[ "ImageCode "] = result;
return result;
}
#endregion

#region 为图片设置干扰点
private void disturbBitmap(Bitmap bitmap)
{
// 通过随机数生成
Random random = new Random();

for (int i = 0; i < bitmap.Width; i++)
{
for (int j = 0; j < bitmap.Height; j++)
{
if (random.Next(100) <= this.fineness)
bitmap.SetPixel(i, j, Color.White);
}
}
}
#endregion

#region 绘制验证码图片
private void drawValidateCode(Bitmap bitmap, string validateCode)
{
// 获取绘制器对象
Graphics g = Graphics.FromImage(bitmap);

// 设置绘制字体
Font font = new Font(fontFamily, fontSize, this.getFontStyle());

// 绘制验证码图像
g.DrawString(validateCode, font, Brushes.Black, posX, posY);


}
#endregion

#region 换算验证码字体样式:1 粗体 2 斜体 3 粗斜体,默认为普通字体
private FontStyle getFontStyle()
{
if (fontStyle == 1)
return FontStyle.Bold;
else if (fontStyle == 2)
return FontStyle.Italic;
else if (fontStyle == 3)
return FontStyle.Bold | FontStyle.Italic;
else
return FontStyle.Regular;
}
#endregion
}

[解决办法]
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;


public partial class validate : System.Web.UI.Page
{
private const int rndLength = 4;
protected void Page_Load(object sender, EventArgs e)
{
// 在此处放置用户代码以初始化页面
string vnum;
vnum = GetByRndNum();
Session[ "validatecode "] = vnum;

Response.ClearContent(); //需要输出图象信息 要修改HTTP头
//Response.BufferOutput = false;
Response.ContentType = "image/Jpeg ";
Response.BinaryWrite(GetByValidateCode(vnum).ToArray());
//Response.Close();

}

private MemoryStream GetByValidateCode(string VNum)//返回内存流
{
Bitmap Img = null;
Graphics g = null;
MemoryStream ms = null;
Random random = new Random();
int gheight = VNum.Length * 12;
Img = new Bitmap(gheight, 20);
g = Graphics.FromImage(Img);
Font f = new Font( "Arial ", 12, FontStyle.Bold);

g.Clear(GetByRandColor(180, 200));//设定背景色
Pen blackPen = new Pen(Color.AntiqueWhite, 1);
//Pen blackPen = new Pen(Color.Black ,1);
for (int i = 0; i < 32; i++)// 随机产生干扰线,使图象中的认证码不易被其它程序探测到
{
int x = random.Next(gheight);
int y = random.Next(20);
int xl = random.Next(6);
int yl = random.Next(12);
g.DrawLine(blackPen, x, y, x + xl, y + yl);
}
SolidBrush s = new SolidBrush(Color.SaddleBrown);
g.DrawString(VNum, f, s, 3, 3);
ms = new MemoryStream();
Img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
g.Dispose();
Img.Dispose();
return ms;
}
//-----------------给定范围获得随机颜色------------
Color GetByRandColor(int fc, int bc)
{
Random random = new Random();

if (fc > 255) fc = 255;
if (bc > 255) bc = 255;
//if(ac> 255) ac=255;
int r = fc + random.Next(bc - fc);
int g = fc + random.Next(bc - fc);
int b = fc + random.Next(bc - bc);
Color rs = Color.FromArgb(r, g, b);
return rs;
}

//-----------------------取随机产生的认证码(N位数字)
public string GetByRndNum()
{
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,w,x,y,z " ;
string[] VcArray = Vchar.Split( ', ');
string VNum = " ";
//采用一个简单的算法以保证生成随机数的不同
Random rand = new Random();
int[] rndArr = new int[rndLength];
for (int i = 1; i < rndLength + 1; i++)


{
if(i> 1)
{
do
{
rndArr[i-1] = rand.Next(10);//rand.Next(35) ;
bool goon = false;
for(int ix=0; ix <i-1; ix++)
{
if (rndArr[ix] == rndArr[i-1])
{
goon = true;
break;
}
}
if (!goon)
break;
} while (1 == 1);
}
else
rndArr[i-1] = rand.Next(10);
VNum += rndArr[i-1];
}
return VNum;
}
}

热点排行