在mvc中实现图片验证码的刷新

时间:2023-03-08 16:50:13

首先,在项目模型(Model)层中建立一个生成图片验证码的类ValidationCodeHelper,代码如下:

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

然后,在控制器(Controller)中创建一个控制器名称为ValidateCodeImgController的.cs文件,写入以下方法。

这个方法用来返回一个图像对象:

        public ActionResult Get()
{
ValidationCodeHelper vCode = new ValidationCodeHelper();
string code;
Image imgcode = vCode.NextImage(,true,out code); //设置临时数据字典进行储存
this.TempData["Code"] = code; //创建存储区为内存的流(关闭程序后,数据会被自动回收)
MemoryStream ms = new MemoryStream(); //将此图像以指定的格式保存到指定的流中
imgcode.Save(ms,ImageFormat.Gif); this.Response.ContentType = "image/gif";
this.Response.BinaryWrite(ms.ToArray());
ms.Close();
imgcode.Dispose(); return new EmptyResult();
}

最后,视图(View)中显示:

js代码:

<script type="text/javascript">
function imgCodes() {
$("#valiCode").attr("src", '@Url.Action("Get", "ValidateCodeImg")'+"?time="+(new Date()).getTime());
}
</script>

html代码:

<td height="" class="login-text02">
验证码:<br />
</td>
<td>
<div style="width:400px;">
<input type="text" name="txtCheck" />&nbsp;&nbsp;&nbsp;
<img id="valiCode" style="cursor: pointer;" src="/ValidateCodeImg/Get" title="看不清,点击换一张" alt="看不清?请点我" onclick="imgCodes(this);" />
&nbsp;&nbsp;
<a href="javascript:imgCodes();">看不清楚,点击这里</a> </div>
</td>

显示效果如下图:

在mvc中实现图片验证码的刷新

注意:根据这段html代码,刷新图片验证码,可以直接点击验证码图片也可以点击a标签。