生成验证码

生成验证码的代码:
public ActionResult ValidCode(){
string strRandom = ValidCodeUtils.GetRandomCode(5);
Session[“validCode”] = strRandom;
byte[] imgByte = ValidCodeUtils.CreateImage(strRandom);
return File(imgByte, @“image/jpeg”);
}

含string那句代码是随机生成5位数的代码,含byte那句代码是根据验证码生成图片,
要想生成验证码和将验证码变成图片,就需要定义一个类:
public static class ValidCodeUtils
{
public static string GetRandomCode(int intLength)
{

        string strReturn = string.Empty;
        Random random = new Random();
        for (int i = 0; i < intLength; i++)
        {
            char cRerult;
            int intRandom = random.Next();
            if (intRandom % 3 == 0)
            {
                cRerult = (char)(0x30 + (intRandom % 10));
            }
            else if (intRandom % 3 == 1)
            {
                cRerult = (char)(0x41 + (intRandom % 0x1a));
            }
            else
            {
                cRerult = (char)(0x61 + (intRandom % 0x1a));
            }
            strReturn += cRerult.ToString();
        }
        return strReturn;
    }
    public static byte[] CreateImage(string strRandom)
    {
        Bitmap newBitmap = new Bitmap(strRandom.Length * 20, 38);

        Graphics g = Graphics.FromImage(newBitmap);
        g.Clear(Color.White);
        SolidBrush solidBrush = new SolidBrush(Color.Red);
        g.DrawString(strRandom, new Font("Aril", 17), solidBrush, 12, 1);
        Random random = new Random();
        for (int i = 0; i < 10; i++)
        {
            int x1 = random.Next(newBitmap.Width);
            int y1 = random.Next(newBitmap.Height);
            int x2 = random.Next(newBitmap.Width);
            int y2 = random.Next(newBitmap.Height);
            g.DrawLine(new Pen(Color.DarkGray), x1, y1, x2, y2);
        }
        for (int i = 0; i < 100; i++)
        {
            int x = random.Next(newBitmap.Width);
            int y = random.Next(newBitmap.Height);
            newBitmap.SetPixel(x, y, Color.FromArgb(random.Next()));
        }
        g.DrawRectangle(new Pen(Color.Blue), 0, 0, newBitmap.Width, newBitmap.Height);
        g.DrawRectangle(new Pen(Color.Blue), -1, -1, newBitmap.Width, newBitmap.Height);
        MemoryStream ms = new MemoryStream();
        newBitmap.Save(ms, ImageFormat.Jpeg);
        return ms.ToArray();
    }
}

最后,去设置鼠标点击图片,图片就会切换:
$("#ValidateCode").click(function () {
$(this).prop(“src”, “/Main/ValidCode?t=” + new Date().getTime());
});

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值