public class ValidateCode

    {

        /// <summary>

        /// 產生圖形驗證碼。

        /// </summary>

        /// <param name="Code">傳出驗證碼。</param>

        /// <param name="CodeLength">驗證碼字元數。</param>

        /// <param name="Width"></param>

        /// <param name="Height"></param>

        /// <param name="FontSize"></param>

        /// <returns></returns>

        public static byte[] CreateValidateGraphic(out String Code, int CodeLength, int Width, int Height, int FontSize)

        {

            String sCode = String.Empty;

            //顏色列表,用於驗證碼、噪線、噪點

            Color[] oColors ={

             System.Drawing.Color.Black,

             System.Drawing.Color.Red,

             System.Drawing.Color.Blue,

             System.Drawing.Color.Green,

             System.Drawing.Color.Orange,

             System.Drawing.Color.Brown,

             System.Drawing.Color.Brown,

             System.Drawing.Color.DarkBlue

            };

            //字體列表,用於驗證碼

            string[] oFontNames = { "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh", "PMingLiU", "Impact" };

            //驗證碼的字元集,去掉了一些容易混淆的字元

            char[] oCharacter = {

       '2','3','4','5','6','8','9',

       'A','B','C','D','E','F','G','H','J','K', 'L','M','N','P','R','S','T','W','X','Y'

      };

            Random oRnd = new Random();

            Bitmap oBmp = null;

            Graphics oGraphics = null;

            int N1 = 0;

            System.Drawing.Point oPoint1 = default(System.Drawing.Point);

            System.Drawing.Point oPoint2 = default(System.Drawing.Point);

            string sFontName = null;

            Font oFont = null;

            Color oColor = default(Color);

//生成驗證碼字串

            for (N1 = 0; N1 <= CodeLength - 1; N1++)

            {

                sCode += oCharacter[oRnd.Next(oCharacter.Length)];

            }

oBmp = new Bitmap(Width, Height);

            oGraphics = Graphics.FromImage(oBmp);

            oGraphics.Clear(System.Drawing.Color.White);

            try

            {

                for (N1 = 0; N1 <= 4; N1++)

                {

                    //畫噪線

                    oPoint1.X = oRnd.Next(Width);

                    oPoint1.Y = oRnd.Next(Height);

                    oPoint2.X = oRnd.Next(Width);

                    oPoint2.Y = oRnd.Next(Height);

                    oColor = oColors[oRnd.Next(oColors.Length)];

                    oGraphics.DrawLine(new Pen(oColor), oPoint1, oPoint2);

                }

float spaceWith = 0, dotX = 0, dotY = 0;

                if (CodeLength != 0)

                {

                    spaceWith = (Width - FontSize * CodeLength - 10) / CodeLength;

                }

for (N1 = 0; N1 <= sCode.Length - 1; N1++)

                {

                    //畫驗證碼字串

                    sFontName = oFontNames[oRnd.Next(oFontNames.Length)];

                    oFont = new Font(sFontName, FontSize, FontStyle.Italic);

                    oColor = oColors[oRnd.Next(oColors.Length)];

dotY = (Height - oFont.Height) / 2 + 2;//中心下移2像素

                    dotX = Convert.ToSingle(N1) * FontSize + (N1 + 1) * spaceWith;

oGraphics.DrawString(sCode[N1].ToString(), oFont, new SolidBrush(oColor), dotX, dotY);

                }

for (int i = 0; i <= 30; i++)

                {

                    //畫噪點

                    int x = oRnd.Next(oBmp.Width);

                    int y = oRnd.Next(oBmp.Height);

                    Color clr = oColors[oRnd.Next(oColors.Length)];

                    oBmp.SetPixel(x, y, clr);

                }

Code = sCode;

                //保存图片数据

                MemoryStream stream = new MemoryStream();

                oBmp.Save(stream, ImageFormat.Jpeg);

                //输出图片流

                return stream.ToArray();

            }

            finally

            {

                oGraphics.Dispose();

            }

        }

    }

//2.2图片流以图片的形式响应到页面

public class ValidateCodeController : Controller

    {

        public ActionResult GetImg()

        {

            int width = ConverterHelper.ObjToInt(Request.Params["width"], 100);

            int height = ConverterHelper.ObjToInt(Request.Params["height"], 40);

            int fontsize = ConverterHelper.ObjToInt(Request.Params["fontsize"], 20);

            string code = string.Empty;

            byte[] bytes = ValidateCode.CreateValidateGraphic(out code, 4, width, height, fontsize);

            SessionHelper.SetValiCode(code);

            return File(bytes, @"image/jpeg");

        }

}

//2.3页面显示及刷新(img+js)

<img id="GL_StandardCode"  style="cursor: pointer;"
src="@Url.Action("GetImg", "ValidateCode")?t=@DateTime.Now.Ticks"
title="看不清,点击换一张" />

$("#GL_StandardCode").click(function () {

                var newSrc = "@Url.Action("GetImg", "ValidateCode")" + "?t=" + (new Date()).getTime();

                this.src=newSrc;

                return false;

            });

//2.4登录时判断SESSION值

string pCode = Request.Params["GL_CodeInput"];

        string sCode = SessionHelper.GetValiCode();

        if (string.IsNullOrEmpty(pCode))

        {

            resultMsg = "请输入验证码";

        }

        else if (string.IsNullOrEmpty(sCode))

        {

            resultMsg = "验证码过期";

        }

        else if (pCode.ToLower() != sCode.ToLower())

        {

            resultMsg = "验证码不正确";

        }

C# mvc 验证码2的更多相关文章

  1. MVC 验证码实现( 简易版)

    现在网站上越来越多的验证码,使用场景也是越来越多,登陆.注册.上传.下载...等等地方,都有可能大量使用到验证码,那么制作验证码到底有多简单呢?我们一起来看下最简易版的验证码实现过程- 验证码的基本步 ...

  2. ASP.NET MVC验证码演示(Ver2)

    前一版本<ASP.NET MVC验证码演示>http://www.cnblogs.com/insus/p/3622116.html,Insus.NET还是使用了Generic handle ...

  3. .NET MVC 验证码

    .NET MVC 验证码

  4. MVC验证码的编写

    主要是相互学习一下mvc,希望各位大神指导 /// <summary> /// 生成随机数字 /// </summary> /// <returns>随机数字< ...

  5. ASP.NET MVC验证码演示

    我们在网站登录或理一个评论时,可以放置一个验证码(Captcha),可以为系统免去那些恶意刷新等功能. 今次Insus.NET在asp.net mvc应用程序实现与演示验证码的产生以及应用等 . 前天 ...

  6. ASP.NET mvc 验证码 (转)

    ASP.net 验证码(C#) MVC http://blog.163.com/xu_shuhao/blog/static/5257748720101022697309/ 网站添加验证码,主要为防止机 ...

  7. mvc验证码图片生成

    /// <summary> ///生成验证码 /// </summary> public class VerifyCode { /// <summary> /// ...

  8. asp.net mvc 验证码

    效果图 验证码类 namespace QJW.VerifyCode { //用法: //public FileContentResult CreateValidate() //{ // Validat ...

  9. 简单C#、asp.net mvc验证码的实现

    using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Text;u ...

  10. C# mvc 验证码3

    //// <summary> /// 生成验证码 /// </summary> /// <param name="length">指定验证码的长 ...

随机推荐

  1. hibernate sql查询

    如果你跟我一样比较熟悉SQL,同时不想学习一门新的语言.那么在hibernate中使用Native SQL 查询也是一种不错的方式. 一方面,Native SQL在效率方面有天生的优势: 另一方面,S ...

  2. [Node] 逃离回调地狱

    逃离Node回调地狱 Background : 在Node中,函数的返回结果大多利用回调的方式处理.如简单的判断文件是否存在并读取内容: var fs = require('fs'); fs.exis ...

  3. 理解标签重置reset

    /*样式表文件来自 懒人css http://lrcss.lrjz100.com *//*---------重置---------*/html{font-size: 100%;-webkit-text ...

  4. I2C和SCCB协议的小区别和误区

    I2C采用的是7位地址数据,首字节最低位代表读写位,第二字节SUB寄存器高位为1表示自动加subaddress SCCB采用的是8位地址数据,比如0x42,B01000010 使用I2C协议时,第一次 ...

  5. 用高德地图API 通过详细地址获得经纬度

    http://cloud.sinyway.com/Service/amap.html http://restapi.amap.com/v3/geocode/geo?key=xxxxxxxxxxxxxx ...

  6. labview中层叠式顺序结构与平铺式顺序结构有什么不同?

    也就看着不同,平铺式看着直观,但比较占地方,程序复杂了就显得过大.二者可互相转换,从这点也可以看出它们没有本质不同!

  7. Android(java)学习笔记183:判断SD卡状态和存储空间大小

    当我们在使用SD卡时候,如果我们想往SD卡里读写数据,我们必须在这之前进行一个逻辑判断,那就是判断SD卡状态和SD存储空间大小: 核心代码: String status = Environment.g ...

  8. WPF – 使用触发器

    WPF – 使用触发器 WPF提供了很重要的一个东西就是绑定Binding, 它帮助我们做了很多事情,这个我们在WPF学习之绑定这篇里边有讲过.对于Binding我们可以设置其绑定对象,关系,并通过某 ...

  9. linux下的oracle数据库和表空间的导入导出

    由于oracle是安装在linux上面,因此需要oracle的导入导出都是使用命令进行操作.oracle允许整个数据库导入导出和表空间的导入导出. 数据库导入导出 以下操作是在操作系统控制台命令中执行 ...

  10. json 是什么

    怎么学习一个知识? 首先要提出几个问题,目前认为json是个什么,json是谁创造的,为什么而出现的,但是目前仅有很长时间之前别人直接告诉我的,json用来存数据的,对于使用也忘记的差不多了,所以现在 ...