c#:mvc使用验证码生成器

4 篇文章 0 订阅

View:

<img id="NumberCode" style="cursor: pointer;" src="@Url.Action("GetNumber", "Login")?width=130&height=34&t=@DateTime.Now.Ticks" title="看不清,点击换一张" />

JS:

$("#NumberCode").click(function () {
    var newSrc = "@Url.Action("GetNumber", "Login")" + "?width=130&height=34&t=" + (new Date()).getTime();
    this.src = newSrc;
    $("#txtCode").val('');//输入的验证码框清空
    return false;
});

Controller:

public ActionResult GetNumber(int width = 100, int height = 40, int fontsize = 20)
{
    string number = string.Empty;
    int numberLength = 4;
    byte[] bytes = CaptchaHelper.CreateValidateGraphic(out number, numberLength, width, height, fontsize);
    Session["number"] = number;
    return File(bytes, @"image/jpeg");
}

Helper:

/// <summary>
/// 验证码生成器
/// </summary>
public class CaptchaHelper
{
    /// <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'
        //};
        char[] oCharacter = {
            '1','2','3','4','5','6','7','8','9','0'
        };
        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();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值