public classValidationCodeHelper
{//用户存取验证码字符串
public string validationCode =String.Empty;
Random ram= newRandom();
Graphics g= null;int bgWidth = 0;int bgHeight = 0;public string FontFace = "Consolas";public int FontSize = 16;public Color foreColor = Color.FromArgb(190, 190, 190);public Color backColor = Color.FromArgb(0, 120, 120);public Color mixedLineColor = Color.FromArgb(220, 220, 220);public int mixedLineWidth = 1;public int mixedLineCount = 3;#region 根据指定长度,返回随机验证码
///
///根据指定长度,返回随机验证码///
/// 制定长度
/// 随即验证码
public string Next(intlength)
{this.validationCode =GetRandomCode(length);return this.validationCode;
}#endregion
#region 根据指定长度及背景图片样式,返回带有随机验证码的图片对象
///
///根据指定长度及背景图片样式,返回带有随机验证码的图片对象///
/// 指定长度
/// 背景图片样式
/// Image对象
public Image NextImage(int length, bool allowMixedLines,out stringcode)
{this.validationCode =GetRandomCode(length);
code= this.validationCode;//System.Web.HttpContext.Current.Session["Code"] = validationCode;//校验码字体
Font myFont = newFont(FontFace, FontSize);//根据校验码字体大小算出背景大小
bgWidth = (int)myFont.Size * length + 4;
bgHeight= (int)myFont.Size * 2;//生成背景图片
Bitmap myBitmap = newBitmap(bgWidth, bgHeight);
g=Graphics.FromImage(myBitmap);this.DrawBackground();this.DrawValidationCode(this.validationCode, myFont);if(allowMixedLines)this.DrawMixedLine();return(Image)myBitmap;
}#endregion
#region 内部方法:绘制验证码背景
private voidDrawBackground( )
{//设置填充背景时用的笔刷
HatchBrush hBrush = newHatchBrush(HatchStyle.Wave, backColor);//填充背景图片
g.FillRectangle(hBrush, 0, 0, this.bgWidth, this.bgHeight);
}#endregion
#region 内部方法:绘制验证码
private void DrawValidationCode(stringvCode, Font font)
{
g.DrawString(vCode, font,new SolidBrush(this.foreColor), 2, 2);
}#endregion
#region 内部方法:绘制干扰线条
///
///绘制干扰线条///
private voidDrawMixedLine()
{for (int i = 0; i < mixedLineCount; i++)
{
g.DrawBezier(new Pen(newSolidBrush(mixedLineColor),mixedLineWidth),
RandomPoint(),
RandomPoint(),
RandomPoint(),
RandomPoint()
);
}
}#endregion
#region 内部方法:返回指定长度的随机验证码字符串
///
///根据指定大小返回随机验证码///
/// 字符串长度
/// 随机字符串
private string GetRandomCode(intlength)
{
StringBuilder sb= new StringBuilder(6);for (int i = 0; i < length; i++)
{
sb.Append(Char.ConvertFromUtf32(RandomAZ09()));
}returnsb.ToString();
}#endregion
#region 内部方法:产生随机数和随机点
///
///产生0-9A-Z的随机字符代码///
/// 字符代码
private intRandomAZ09()
{//Thread.Sleep(15);
int result = 48;int i = ram.Next(2);switch(i)
{case 0:
result= ram.Next(48, 58);break;case 1:
result= ram.Next(65, 91);break;
}returnresult;
}///
///返回一个随机点,该随机点范围在验证码背景大小范围内///
/// Point对象
privatePoint RandomPoint()
{//Thread.Sleep(15);
Point point= new Point(ram.Next(this.bgWidth), ram.Next(this.bgHeight));returnpoint;
}#endregion}