码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2015-06-21 19:48:56      阅读:271      评论:0      收藏:0      [点我收藏+]

标签:

 

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

 public class ValidationCodeHelper
    {
        //用户存取验证码字符串 
        public string validationCode = String.Empty;
        Random ram = new Random();
        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 根据指定长度,返回随机验证码
        /// <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 + 4;
            bgHeight = (int)myFont.Size * 2;
            //生成背景图片 
            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, 0, 0, this.bgWidth, this.bgHeight);
        }
        #endregion


        #region 内部方法:绘制验证码
        private void DrawValidationCode(string vCode, Font font)
        {
            g.DrawString(vCode, font, new SolidBrush(this.foreColor), 2, 2);
        }
        #endregion


        #region 内部方法:绘制干扰线条
        /// <summary> 
        /// 绘制干扰线条 
        /// </summary> 
        private void DrawMixedLine()
        {
            for (int i = 0; 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(6);

            for (int i = 0; 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 = 48;
            
            int i = ram.Next(2);

            switch (i)
            {
                case 0:
                    result = ram.Next(48, 58);
                    break;
                case 1:
                    result = ram.Next(65, 91);
                    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(4,true,out code);

            //使用Session进行储存
            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="35" 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>

 显示效果如下图:

技术分享

 

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

 

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

标签:

原文地址:http://www.cnblogs.com/cghjy/p/4592297.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!