務必收藏備用:.net core中通過Json或直接獲取圖形驗證碼(數字驗證碼、字母驗證碼、混合驗證碼),有源代碼全實戰demo(開源代碼.net core3.0)

来源:https://www.cnblogs.com/jiyuwu/archive/2019/11/06/11803979.html
-Advertisement-
Play Games

很多人寫的博客大家看了會一知半解,不知道怎麼用,應該引用什麼類庫或者代碼不全,這樣很多小白很是頭疼,尤其是嘗新技術更是如此。我們這邊不止告訴你步驟,而且還提供開源demo。隨著時間的推移,我們的demo庫會日益強大請及時收藏GitHub。 1.首先你需要Nuget引用類庫 Install-Packa ...


很多人寫的博客大家看了會一知半解,不知道怎麼用,應該引用什麼類庫或者代碼不全,這樣很多小白很是頭疼,尤其是嘗新技術更是如此。我們這邊不止告訴你步驟,而且還提供開源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.效果如圖

 

 

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...