hi,你好!欢迎访问本站!登录
本站由网站地图腾讯云宝塔系统阿里云强势驱动
当前位置:首页 - 教程 - 杂谈 - 正文 君子好学,自强不息!

务必珍藏备用:.net core中经由过程Json或直接猎取图形验证码(数字验证码、字母验证码、夹杂验证码),有源代码全实战demo(开源代码.net core3.0)

2019-11-18杂谈搜奇网54°c
A+ A-

许多人写的博客人人看了会一孔之见,不知道怎样用,应当援用什么类库或许代码不全,如许许多小白非常头疼,尤其是尝新手艺更是如此。我们这边不止通知你步骤,而且还供应开源demo。跟着时候的推移,我们的demo库会日趋壮大请实时珍藏GitHub

1.起首你须要Nuget援用类库

Install-Package ZKWeb.System.Drawing -Version 4.0.1

2.建立大众类VerifyCodeHelper和CommonHelper

(1)CommonHelper中增加图形处置惩罚要领

#region 验证码
        public static byte[] Bitmap2Byte(Bitmap bitmap)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Jpeg);
                byte[] data = new byte[stream.Length];
                stream.Seek(0, SeekOrigin.Begin);
                stream.Read(data, 0, Convert.ToInt32(stream.Length));
                return data;
            }
        }
        #endregion
public static string CodeJson(string code, string msg)
        {
            return "{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\"}";
        }

 (2)VerifyCodeHelper增加图形处置惩罚要领

public  class VerifyCodeHelper
    {
        #region 单例形式
        //建立私有化静态obj锁  
        private static readonly object _ObjLock = new object();
        //建立私有静态字段,吸收类的实例化对象  
        private static VerifyCodeHelper _VerifyCodeHelper = null;
        //组织函数私有化  
        private VerifyCodeHelper() { }
        //建立单利对象资本并返回  
        public static VerifyCodeHelper GetSingleObj()
        {
            if (_VerifyCodeHelper == null)
            {
                lock (_ObjLock)
                {
                    if (_VerifyCodeHelper == null)
                        _VerifyCodeHelper = new VerifyCodeHelper();
                }
            }
            return _VerifyCodeHelper;
        }
        #endregion

        #region 生产验证码
        public enum VerifyCodeType { NumberVerifyCode, AbcVerifyCode, MixVerifyCode };

        /// <summary>
        /// 1.数字验证码
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private string CreateNumberVerifyCode(int length)
        {
            int[] randMembers = new int[length];
            int[] validateNums = new int[length];
            string validateNumberStr = "";
            //生成肇端序列值  
            int seekSeek = unchecked((int)DateTime.Now.Ticks);
            Random seekRand = new Random(seekSeek);
            int beginSeek = seekRand.Next(0, Int32.MaxValue - length * 10000);
            int[] seeks = new int[length];
            for (int i = 0; i < length; i++)
            {
                beginSeek += 10000;
                seeks[i] = beginSeek;
            }
            //生成随机数字  
            for (int i = 0; i < length; i++)
            {
                Random rand = new Random(seeks[i]);
                int pownum = 1 * (int)Math.Pow(10, length);
                randMembers[i] = rand.Next(pownum, Int32.MaxValue);
            }
            //抽取随机数字  
            for (int i = 0; i < length; i++)
            {
                string numStr = randMembers[i].ToString();
                int numLength = numStr.Length;
                Random rand = new Random();
                int numPosition = rand.Next(0, numLength - 1);
                validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
            }
            //生成验证码  
            for (int i = 0; i < length; i++)
            {
                validateNumberStr += validateNums[i].ToString();
            }
            return validateNumberStr;
        }

        /// <summary>
        /// 2.字母验证码
        /// </summary>
        /// <param name="length">字符长度</param>
        /// <returns>验证码字符</returns>
        private string CreateAbcVerifyCode(int length)
        {
            char[] verification = new char[length];
            char[] dictionary = { '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',
                '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'
            };
            Random random = new Random();
            for (int i = 0; i < length; i++)
            {
                verification[i] = dictionary[random.Next(dictionary.Length - 1)];
            }
            return new string(verification);
        }

        /// <summary>
        /// 3.夹杂验证码
        /// </summary>
        /// <param name="length">字符长度</param>
        /// <returns>验证码字符</returns>
        private string CreateMixVerifyCode(int length)
        {
            char[] verification = new char[length];
            char[] dictionary = { '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'
            };
            Random random = new Random();
            for (int i = 0; i < length; i++)
            {
                verification[i] = dictionary[random.Next(dictionary.Length - 1)];
            }
            return new string(verification);
        }

        /// <summary>
        /// 发生验证码(随机发生4-6位)
        /// </summary>
        /// <param name="type">验证码范例:数字,字符,相符</param>
        /// <returns></returns>
        public string CreateVerifyCode(VerifyCodeType type)
        {
            string verifyCode = string.Empty;
            Random random = new Random();
            int length = random.Next(4, 6);
            switch (type)
            {
                case VerifyCodeType.NumberVerifyCode:
                    verifyCode = GetSingleObj().CreateNumberVerifyCode(length);
                    break;
                case VerifyCodeType.AbcVerifyCode:
                    verifyCode = GetSingleObj().CreateAbcVerifyCode(length);
                    break;
                case VerifyCodeType.MixVerifyCode:
                    verifyCode = GetSingleObj().CreateMixVerifyCode(length);
                    break;
            }
            return verifyCode;
        }
        #endregion

        #region 验证码图片
        /// <summary>
        /// 验证码图片 => Bitmap
        /// </summary>
        /// <param name="verifyCode">验证码</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns>Bitmap</returns>
        public Bitmap CreateBitmapByImgVerifyCode(string verifyCode, int width, int height)
        {
            Font font = new Font("Arial", 14, (FontStyle.Bold | FontStyle.Italic));
            Brush brush;
            Bitmap bitmap = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bitmap);
            SizeF totalSizeF = g.MeasureString(verifyCode, font);
            SizeF curCharSizeF;
            PointF startPointF = new PointF(0, (height - totalSizeF.Height) / 2);
            Random random = new Random(); //随机数发生器
            g.Clear(Color.White); //清空图片背景色  
            for (int i = 0; i < verifyCode.Length; i++)
            {
                brush = new LinearGradientBrush(new Point(0, 0), new Point(1, 1), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255)), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255)));
                g.DrawString(verifyCode[i].ToString(), font, brush, startPointF);
                curCharSizeF = g.MeasureString(verifyCode[i].ToString(), font);
                startPointF.X += curCharSizeF.Width;
            }

            //画图片的滋扰线  
            for (int i = 0; i < 10; i++)
            {
                int x1 = random.Next(bitmap.Width);
                int x2 = random.Next(bitmap.Width);
                int y1 = random.Next(bitmap.Height);
                int y2 = random.Next(bitmap.Height);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            //画图片的远景滋扰点  
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(bitmap.Width);
                int y = random.Next(bitmap.Height);
                bitmap.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1); //画图片的边框线  
            g.Dispose();
            return bitmap;
        }

        /// <summary>
        /// 验证码图片 => byte[]
        /// </summary>
        /// <param name="verifyCode">验证码</param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        /// <returns>byte[]</returns>
        public byte[] CreateByteByImgVerifyCode(string verifyCode, int width, int height)
        {
            Font font = new Font("Arial", 14, (FontStyle.Bold | FontStyle.Italic));
            Brush brush;
            Bitmap bitmap = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bitmap);
            SizeF totalSizeF = g.MeasureString(verifyCode, font);
            SizeF curCharSizeF;
            PointF startPointF = new PointF(0, (height - totalSizeF.Height) / 2);
            Random random = new Random(); //随机数发生器
            g.Clear(Color.White); //清空图片背景色  
            for (int i = 0; i < verifyCode.Length; i++)
            {
                brush = new LinearGradientBrush(new Point(0, 0), new Point(1, 1), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255)), Color.FromArgb(random.Next(255), random.Next(255), random.Next(255)));
                g.DrawString(verifyCode[i].ToString(), font, brush, startPointF);
                curCharSizeF = g.MeasureString(verifyCode[i].ToString(), font);
                startPointF.X += curCharSizeF.Width;
            }

            //画图片的滋扰线  
            for (int i = 0; i < 10; i++)
            {
                int x1 = random.Next(bitmap.Width);
                int x2 = random.Next(bitmap.Width);
                int y1 = random.Next(bitmap.Height);
                int y2 = random.Next(bitmap.Height);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            //画图片的远景滋扰点  
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(bitmap.Width);
                int y = random.Next(bitmap.Height);
                bitmap.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            g.DrawRectangle(new Pen(Color.Silver), 0, 0, bitmap.Width - 1, bitmap.Height - 1); //画图片的边框线  
            g.Dispose();

            //保留图片数据  
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Jpeg);
            //输出图片流  
            return stream.ToArray();

        }
        #endregion

3.背景控制器依据要求返回响应图形数据

 #region 验证码

        #region 夹杂验证码

        [HttpGet]
        public string MixVerifyCodeJson()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.MixVerifyCode);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            byte[] imgBt = CommonHelper.Bitmap2Byte(bitmap);
            string uuid = Guid.NewGuid().ToString();
            return CommonHelper.CodeJson(uuid, Convert.ToBase64String(imgBt));
        }
        [HttpGet]
        public IActionResult MixVerifyCode()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.MixVerifyCode);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Png);
            return File(stream.ToArray(), "image/png");
        }
        #endregion

        #region 数字验证码
        [HttpGet]
        public string NumberVerifyCodeJson()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            byte[] imgBt = CommonHelper.Bitmap2Byte(bitmap);
            string uuid = Guid.NewGuid().ToString();
            return CommonHelper.CodeJson(uuid, Convert.ToBase64String(imgBt));
        }
        [HttpGet]
        public IActionResult NumberVerifyCode()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Png);
            return File(stream.ToArray(), "image/png");
        }
        #endregion

        #region 字母验证码
        [HttpGet]
        public IActionResult AbcVerifyCode()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.AbcVerifyCode);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            MemoryStream stream = new MemoryStream();
            bitmap.Save(stream, ImageFormat.Png);
            return File(stream.ToArray(), "image/png");
        }
        [HttpGet]
        public string AbcVerifyCodeJson()
        {
            string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.AbcVerifyCode);
            var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 40);
            byte[] imgBt = CommonHelper.Bitmap2Byte(bitmap);
            string uuid = Guid.NewGuid().ToString();
            return CommonHelper.CodeJson(uuid, Convert.ToBase64String(imgBt));
        }
        #endregion

        #endregion

4.前端要求分为直接要求文件或json图形数据并衬着至Img标签

<script type="text/javascript">
    $(function () {
        refreshNumJson();
        refreshMixJson();
        refreshAbcJson();
    });
    function refreshNum() {
        var id = document.getElementById("numImg");
        var str = "/Verify/NumberVerifyCode?random=" + Math.random();
        id.setAttribute("src", str);
    }
    function refreshNumJson() {
        $.ajax({
            type: "get",
            contentType: 'application/json',
            url: '/Verify/NumberVerifyCodeJson?' + Math.random(),
            dataType: 'json',
            async: false,
            success: function (data) {
                $("#numImgJson").attr("src", "data:image/png;base64," + data.msg);
                console.log(data.code);
            },
            error: function (xhr) {
                console.log(xhr.responseText);
            }
        });
    }

    function refreshMix() {
        var id = document.getElementById("mixImg");
        var str = "/Verify/MixVerifyCode?random=" + Math.random();
        id.setAttribute("src", str);
    }
    function refreshMixJson() {
        $.ajax({
            type: "get",
            contentType: 'application/json',
            url: '/Verify/MixVerifyCodeJson?' + Math.random(),
            dataType: 'json',
            async: false,
            success: function (data) {
                $("#mixImgJson").attr("src", "data:image/png;base64," + data.msg);
                console.log(data.code);
            },
            error: function (xhr) {
                console.log(xhr.responseText);
            }
        });
    }

    function refreshAbc() {
        var id = document.getElementById("abcImg");
        var str = "/Verify/AbcVerifyCode?random=" + Math.random();
        id.setAttribute("src", str);
    }
    function refreshAbcJson() {
        $.ajax({
            type: "get",
            contentType: 'application/json',
            url: '/Verify/AbcVerifyCodeJson?' + Math.random(),
            dataType: 'json',
            async: false,
            success: function (data) {
                $("#abcImgJson").attr("src", "data:image/png;base64," + data.msg);
                console.log(data.code);
            },
            error: function (xhr) {
                console.log(xhr.responseText);
            }
        });
    }
</script>


<h2>图形数字验证码</h2>
<img id="numImgJson" title="数字验证码Json猎取"
     alt="vcode" style="cursor:pointer;" onclick="refreshNumJson()" />
<a href="javascript:void(0);" onclick="refreshNumJson()">看不清,换一张</a>
<img id="numImg" title="数字验证码" src="/Verify/NumberVerifyCode?random=1994"
     alt="vcode" style="cursor:pointer;" onclick="refreshNum()" />
<a href="javascript:void(0);" onclick="refreshNum()">看不清,换一张</a>
<h2>图形字母验证码</h2>
<img id="abcImgJson" title="图形字母验证码Json猎取"
     alt="vcode" style="cursor:pointer;" onclick="refreshAbcJson()" />
<a href="javascript:void(0);" onclick="refreshAbcJson()">看不清,换一张</a>
<img id="abcImg" title="图形字母验证码" src="/Verify/AbcVerifyCode?random=1994"
     alt="vcode" style="cursor:pointer;" onclick="refreshAbc()" />
<a href="javascript:void(0);" onclick="refreshAbc()">看不清,换一张</a>
<h2>图形夹杂验证码</h2>
<img id="mixImgJson" title="图形夹杂验证码Json猎取"
     alt="vcode" style="cursor:pointer;" onclick="refreshMixJson()" />
<a href="javascript:void(0);" onclick="refreshMixJson()">看不清,换一张</a>
<img id="mixImg" title="图形夹杂验证码" src="/Verify/MixVerifyCode?random=1994"
     alt="vcode" style="cursor:pointer;" onclick="refreshMix()" />
<a href="javascript:void(0);" onclick="refreshMix()">看不清,换一张</a>

5.结果如图

 

 开源地点 动动小手,点个引荐吧!

注重:我们时机屋该项目将历久为人人供应asp.net core种种好用demo,旨在协助.net开辟者提拔竞争力和开辟速率,发起尽早珍藏该模板鸠合项目。

  选择打赏方式
微信赞助

打赏

QQ钱包

打赏

支付宝赞助

打赏

  移步手机端
务必珍藏备用:.net core中经由过程Json或直接猎取图形验证码(数字验证码、字母验证码、夹杂验证码),有源代码全实战demo(开源代码.net core3.0)

1、打开你手机的二维码扫描APP
2、扫描左则的二维码
3、点击扫描获得的网址
4、可以在手机端阅读此文章
未定义标签

本文来源:搜奇网

本文地址:https://www.sou7.cn/282377.html

关注我们:微信搜索“搜奇网”添加我为好友

版权声明: 本文仅代表作者个人观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。请记住本站网址https://www.sou7.cn/搜奇网。

发表评论

选填

必填

必填

选填

请拖动滑块解锁
>>