ASP.NET Core生成好看的图形验证码

引言

ASP.NET Core的验证码呢,稍微有一点曲折,因为默认System.Drawing没有Bitmap对象,也就没法绘制对象,不过通过NuGetZKWeb.System.Drawing 可引入Bitmap对象,进行验证码图片绘制

在这里插入图片描述

一、生成随机数

随机数就比较简单了,给定特定的字符数组,通过Random来生成随机数拼接成对应的字符串,就得到了我们的随验证码的随即字符,这里我简单进行了封装,仅供参考!

        /// <summary>
        /// 获取数字验证码
        /// </summary>
        /// <param name="n">验证码数</param>
        /// <returns></returns>
        public static string CreateNumCode(int n)
        {
            char[] numChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            string charCode = string.Empty;

            Random random = new Random();

            for (int i = 0; i < n; i++)
            {
                charCode += numChar[random.Next(numChar.Length)];
            }
            return charCode;
        }

        /// <summary>
        /// 获取字符验证码
        /// </summary>
        /// <param name="n">验证码数</param>
        /// <returns></returns>
        public static string CreateCharCode(int n)
        {
            char[] strChar = { 'a', 'b','c','d','e','f','g','h','i','j','k','l','m',
                'n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3',
                '4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K',
                'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

            string charCode = string.Empty;

            Random random = new Random();

            for (int i = 0; i < n; i++)
            {
                charCode += strChar[random.Next(strChar.Length)];
            }
            return charCode;
        }

二、绘制图片

绘制图片也就是所谓的验证码对于新手就比较陌生了,不过也很好理解,通过简单的梳理下逻辑步骤,就可以清晰明了。即:通过Bitmap创建画布Graphis执行画的动作,如:验证码的躁线噪点呈现的字符,通过MemoryStream写入内存,通过MemoryStream转换的数据去获取生成的对应验证码图,再用SessionCookie存储验证码即可完成!

1、画布

通过Bitmap对象创建画布

            //创建画布
            Bitmap bitmap = new Bitmap(codeW, codeH);
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.Clear(Color.White);

2、画躁线

躁线可提高验证码的可用性,通过给Graphics画笔Pen指定颜色位置即可完成!

            //颜色列表
            Color[] colors = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue };
           
            //宽、高,字体大小
            int codeW = 74;
            int codeH = 36;
            int fontSize = 16;
            Random random = new Random();

            //画躁线
            for (int i = 0; i < n; i++)
            {
                int x1 = random.Next(codeW);
                int y1 = random.Next(codeH);
                int x2 = random.Next(codeW);
                int y2 = random.Next(codeH);
                Color color = colors[random.Next(colors.Length)];
                Pen pen = new Pen(color);
                graphics.DrawLine(pen, x1, y1, x2, y2);
            }

3、画噪点

噪点和躁线原理一致,不过这里要使用的是BitmapSetPixel来完成,很简单也很好理解!

            //画噪点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(codeW);
                int y = random.Next(codeH);
                Color color = colors[random.Next(colors.Length)];
                bitmap.SetPixel(x, y, color);
            }

4、画验证码

            //画验证码
            for (int i = 0; i < n; i++)
            {
                string fontStr = fonts[random.Next(fonts.Length)];
                Font font = new Font(fontStr, fontSize);
                Color color = colors[random.Next(colors.Length)];
                graphics.DrawString(charCode[i].ToString(), font, new SolidBrush(color), (float)i * 15 + 2, (float)0);
            }

            //写入内存流
            try
            {
                MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, ImageFormat.Jpeg);

                VerifyCode verifyCode = new VerifyCode()
                {
                    Code = charCode,
                    Image = stream.ToArray()
                };
                return verifyCode;
            }

            //释放资源
            finally
            {
                graphics.Dispose();
                bitmap.Dispose();
            }

三、完整代码示例

上述是分布讲解图形验证码的生成过程,以及组成结构,这里提供完整的代码,以供大家参考和应用!一共三部分:验证码结构、枚举类型(NUM:数字验证码,CHAR字符验证码),工具类,并提供Web调用代码!

public class VerifyCode
    {
        /// <summary>
        /// 验证码
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 验证码数据流
        /// </summary>
        public byte[] Image { get; set; }
    }
public enum VerifyCodeType
    {
        NUM,
        CHAR
    }
public static class VerifyCodeHelper
    {
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="n">验证码数</param>
        /// <param name="type">类型 0:数字 1:字符</param>
        /// <returns></returns>
        public static VerifyCode CreateVerifyCode(int n, VerifyCodeType type)
        {
            //宽、高,字体大小
            int codeW = 74;
            int codeH = 36;
            int fontSize = 16;

            //初始化验证码
            string charCode = string.Empty;

            switch (type.ToString())
            {
                case "NUM":
                    charCode = CreateNumCode(n);
                    break;
                default:
                    charCode = CreateCharCode(n);
                    break;
            }

            //颜色列表
            Color[] colors = { Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange, Color.Brown, Color.DarkBlue };

            //字体列表
            string[] fonts = { "Times New Roman", "Verdana", "Arial", "Gungsuh" };

            //创建画布
            Bitmap bitmap = new Bitmap(codeW, codeH);
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.Clear(Color.White);

            Random random = new Random();

            //画躁线
            for (int i = 0; i < n; i++)
            {
                int x1 = random.Next(codeW);
                int y1 = random.Next(codeH);
                int x2 = random.Next(codeW);
                int y2 = random.Next(codeH);
                Color color = colors[random.Next(colors.Length)];
                Pen pen = new Pen(color);
                graphics.DrawLine(pen, x1, y1, x2, y2);
            }          

            //画噪点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(codeW);
                int y = random.Next(codeH);
                Color color = colors[random.Next(colors.Length)];
                bitmap.SetPixel(x, y, color);
            }

            //画验证码
            for (int i = 0; i < n; i++)
            {
                string fontStr = fonts[random.Next(fonts.Length)];
                Font font = new Font(fontStr, fontSize);
                Color color = colors[random.Next(colors.Length)];
                graphics.DrawString(charCode[i].ToString(), font, new SolidBrush(color), (float)i * 15 + 2, (float)0);
            }

            //写入内存流
            try
            {
                MemoryStream stream = new MemoryStream();
                bitmap.Save(stream, ImageFormat.Jpeg);

                VerifyCode verifyCode = new VerifyCode()
                {
                    Code = charCode,
                    Image = stream.ToArray()
                };
                return verifyCode;
            }

            //释放资源
            finally
            {
                graphics.Dispose();
                bitmap.Dispose();
            }

        }

        /// <summary>
        /// 获取数字验证码
        /// </summary>
        /// <param name="n">验证码数</param>
        /// <returns></returns>
        public static string CreateNumCode(int n)
        {
            char[] numChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            string charCode = string.Empty;

            Random random = new Random();

            for (int i = 0; i < n; i++)
            {
                charCode += numChar[random.Next(numChar.Length)];
            }
            return charCode;
        }

        /// <summary>
        /// 获取字符验证码
        /// </summary>
        /// <param name="n">验证码数</param>
        /// <returns></returns>
        public static string CreateCharCode(int n)
        {
            char[] strChar = { 'a', 'b','c','d','e','f','g','h','i','j','k','l','m',
                'n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3',
                '4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K',
                'L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};

            string charCode = string.Empty;

            Random random = new Random();

            for (int i = 0; i < n; i++)
            {
                charCode += strChar[random.Next(strChar.Length)];
            }
            return charCode;
        }

    }
public class VerifyCodeController : Controller
    {
        public async Task<FileResult> GetVerifyCode()
        {
            var oldVerifyCode = HttpContext.Session.GetString("VerifyCode");
            if (!string.IsNullOrEmpty(oldVerifyCode))
            {
                HttpContext.Session.SetString("VerifyCode", "");
            }
            return await Task.Factory.StartNew(() =>
            {
                VerifyCode verifyCode = VerifyCodeHelper.CreateVerifyCode(4, VerifyCodeType.CHAR);
                HttpContext.Session.SetString("VerifyCode", verifyCode.Code);
                return File(verifyCode.Image, @"image/jpeg"); ;
            });
        }
    }
<img src="/VerifyCode/GetVerifyCode" onclick="this.src=this.src+'?'"/>

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: ASP.NETASP.NET Core是两个不同的Web应用程序框架。ASP.NET是Microsoft开发的一种Web应用程序框架,而ASP.NET CoreASP.NET的下一代版本。 ASP.NET是基于.NET Framework的,而ASP.NET Core是跨平台的,可以在Windows、Linux和macOS上运行。ASP.NET Core还具有更快的性能、更好的可扩展性和更好的安全性。 ASP.NET Core还提供了一种新的开发模型,即基于中间件的管道模型,这使得开发人员可以更轻松地构建和配置Web应用程序。此外,ASP.NET Core还提供了一种新的依赖注入系统,使得开发人员可以更轻松地管理应用程序中的依赖关系。 总之,ASP.NETASP.NET Core都是用于构建Web应用程序的框架,但它们之间存在一些重要的区别,包括支持的平台、性能、可扩展性和开发模型等方面。 ### 回答2: ASP.NETASP.NET Core都是Microsoft公司开发的Web应用程序框架,两者之间有很多不同之处。这篇文章将讨论它们之间的这些不同点。 1. 跨平台支持: ASP.NET是运行在Windows操作系统上的Web应用程序框架,而ASP.NET Core则是跨平台的。因此,在MacOS和Linux等其他操作系统上也可以使用ASP.NET Core。 2. 依赖的第三方库: ASP.NET依赖于大量的第三方库和框架,这些库可以添加到项目中以增强其功能。但是ASP.NET Core开发人员更多的将自己的应用程序依赖配置在库中,例如,.NET中的NuGet包。 3. 性能: 相比ASP.NETASP.NET Core更快,更高效。其中一个原因是,ASP.NET Core不需要与IIS(Internet Information Services)进行交互,这意味着更少的资源被分配, 4. 打包: ASP.NETASP.NET Core都可以使用NuGet包管理器来进行打包,但是ASP.NET Core可以将其应用程序打包为单个可执行文件,这使得开发和部署更加容易。 5. 依赖的编程语言: ASP.NET Core只能使用C#和F#等可将代码编译为.NET Core的语言,而ASP.NET则可以使用任何可编译为.NET框架的语言,包括C#,VB.NET和C++。 6. JWT的授权: 在ASP.NET Core中,JSON Web Token(JWT)是第一类公民,而在ASP.NET中,它只能使用第三方库进行实现。 7. MVC: 在ASP.NET Core中,MVC(Model-View-Controller)是默认的Web应用程序架构,但是在ASP.NET中,MVC需要安装一个独立的模板。 8. 版本: ASP.NET Core是最新的Web应用程序框架,而ASP.NET是较旧的。因此,ASP.NET Core提供了更多的功能和性能,而ASP.NET则使用固定的框架版本。 总之,虽然两者都是Microsoft公司开发的Web应用程序框架,但是它们之间还是有很多不同之处。因此,选择使用哪个框架取决于项目的要求,例如,是否需要跨平台支持和性能等。 ### 回答3: ASP.NET是一种Web应用程序框架,由Microsoft公司推出,它是Microsoft .NET运行时环境的一部分。ASP.NET提供了丰富的开发工具和框架,包括Web Forms、MVC、Web API等。它通常与IIS(Internet Information Services)一起使用,作为Web服务器上的应用程序。 ASP.NET Core是一个开源的、跨平台的Web应用程序框架,也是由Microsoft公司推出。它是Architecture Unified(一体化架构)领域的一项重要创新。ASP.NET Core是.NET平台上的一个新的、轻量级Web框架,可以跨平台运行在Windows、macOS和Linux等操作系统上。它同时支持Web Forms、MVC和Web API等多种编程模型,具有高度灵活性和可扩展性。 下面我们来详细看一下ASP.NETASP.NET Core的区别: 1.跨平台性:ASP.NET只能运行在Windows环境下,而ASP.NET Core可以运行在Windows、Linux和macOS等操作系统上。 2.开源性:ASP.NET是Microsoft公司的闭源产品,而ASP.NET Core是一个开源的多平台Web框架,所有代码都进行了公开。 3.轻量级:ASP.NET Core是一个轻量级的框架,文件大小比ASP.NET小很多,启动速度也更快。而ASP.NET则是重量级的框架,需要较高的硬件配置和更长的启动时间。 4.性能:ASP.NET Core的性能比ASP.NET更好,这是因为它是一个基于模块化设计的框架。模块化设计使得ASP.NET Core可以更容易地进行优化和扩展,而且运行时内存的消耗也更小。 5.配置简单:ASP.NET Core的配置更加简单,可以使用依赖注入模式来配置应用程序。而ASP.NET则需要在Web.config中进行大量的配置。 6.兼容性:ASP.NET Core不支持Web Forms的开发模式,而ASP.NET支持Web Forms、MVC和Web API等多种开发模式。 综上所述,ASP.NETASP.NET Core的最大区别在于跨平台性、开源性、轻量级、性能和配置的简单等方面。ASP.NET Core是一个新的、基于模块化设计的Web框架,具有更高的性能、更好的跨平台性和更简单的配置,未来将会成为ASP.NET的主要发展方向。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值