欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

务必收藏备用:.net core中通过Json或直接获取图形验证码(数字验证码、字母验证码、混合验证码),有源代码全实战demo(开源代码.net core3.0)

程序员文章站 2022-08-28 12:53:20
很多人写的博客大家看了会一知半解,不知道怎么用,应该引用什么类库或者代码不全,这样很多小白很是头疼,尤其是尝新技术更是如此。我们这边不止告诉你步骤,而且还提供开源demo。随着时间的推移,我们的demo库会日益强大请及时收藏GitHub。 1.首先你需要Nuget引用类库 Install-Packa ......

很多人写的博客大家看了会一知半解,不知道怎么用,应该引用什么类库或者代码不全,这样很多小白很是头疼,尤其是尝新技术更是如此。我们这边不止告诉你步骤,而且还提供开源demo。随着时间的推移,我们的demo库会日益强大请及时收藏github

1.首先你需要nuget引用类库

install-package zkweb.system.drawing -version 4.0.1

2.创建公共类verifycodehelper和commonhelper

务必收藏备用:.net core中通过Json或直接获取图形验证码(数字验证码、字母验证码、混合验证码),有源代码全实战demo(开源代码.net core3.0)

(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.效果如图

务必收藏备用:.net core中通过Json或直接获取图形验证码(数字验证码、字母验证码、混合验证码),有源代码全实战demo(开源代码.net core3.0)

 

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

注意:我们机遇屋该项目将长期为大家提供asp.net core各种好用demo,旨在帮助.net开发者提升竞争力和开发速度,建议尽早收藏该模板集合项目