這篇文章將為大家詳細(xì)講解有關(guān).NET Core 2.0怎樣生成圖片驗(yàn)證碼,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
創(chuàng)新互聯(lián)建站主營(yíng)常山網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,重慶APP軟件開發(fā),常山h5成都小程序開發(fā)搭建,常山網(wǎng)站營(yíng)銷推廣歡迎常山等地區(qū)企業(yè)咨詢.NET Core 2.0生成圖片驗(yàn)證碼
NuGet包引入:ZKWeb.System.Drawing,如下所示:
代碼實(shí)例如下:VerifyCodeHelper
using System; using System.DrawingCore; using System.DrawingCore.Drawing2D; using System.DrawingCore.Imaging; using System.IO; namespace Common.Helper { public sealed class VerifyCodeHelper { #region 單例模式 //創(chuàng)建私有化靜態(tài)obj鎖 private static readonly object _ObjLock = new object(); //創(chuàng)建私有靜態(tài)字段,接收類的實(shí)例化對(duì)象 private static VerifyCodeHelper _VerifyCodeHelper = null; //構(gòu)造函數(shù)私有化 private VerifyCodeHelper() { } //創(chuàng)建單利對(duì)象資源并返回 public static VerifyCodeHelper GetSingleObj() { if (_VerifyCodeHelper == null) { lock (_ObjLock) { if (_VerifyCodeHelper == null) _VerifyCodeHelper = new VerifyCodeHelper(); } } return _VerifyCodeHelper; } #endregion #region 生產(chǎn)驗(yàn)證碼 public enum VerifyCodeType { NumberVerifyCode, AbcVerifyCode, MixVerifyCode }; /// <summary> /// 1.數(shù)字驗(yàn)證碼 /// </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; } //生成隨機(jī)數(shù)字 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); } //抽取隨機(jī)數(shù)字 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)); } //生成驗(yàn)證碼 for (int i = 0; i < length; i++) { validateNumberStr += validateNums[i].ToString(); } return validateNumberStr; } /// <summary> /// 2.字母驗(yàn)證碼 /// </summary> /// <param name="length">字符長(zhǎng)度</param> /// <returns>驗(yàn)證碼字符</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.混合驗(yàn)證碼 /// </summary> /// <param name="length">字符長(zhǎng)度</param> /// <returns>驗(yàn)證碼字符</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> /// 產(chǎn)生驗(yàn)證碼(隨機(jī)產(chǎn)生4-6位) /// </summary> /// <param name="type">驗(yàn)證碼類型:數(shù)字,字符,符合</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 驗(yàn)證碼圖片 /// <summary> /// 驗(yàn)證碼圖片 => Bitmap /// </summary> /// <param name="verifyCode">驗(yàn)證碼</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(); //隨機(jī)數(shù)產(chǎn)生器 g.Clear(Color.White); //清空?qǐng)D片背景色 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); } //畫圖片的前景干擾點(diǎn) 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> /// 驗(yàn)證碼圖片 => byte[] /// </summary> /// <param name="verifyCode">驗(yàn)證碼</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(); //隨機(jī)數(shù)產(chǎn)生器 g.Clear(Color.White); //清空?qǐng)D片背景色 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); } //畫圖片的前景干擾點(diǎn) 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(); //保存圖片數(shù)據(jù) MemoryStream stream = new MemoryStream(); bitmap.Save(stream, ImageFormat.Jpeg); //輸出圖片流 return stream.ToArray(); } #endregion } }
新建控制器:VerifyCodeController,
using System.DrawingCore.Imaging; using System.IO; using Common.Helper; using Microsoft.AspNetCore.Mvc; namespace WebApplicationApi.Controllers { public class VerifyCodeController : Controller { public IActionResult Index() { return View(); } /// <summary> /// 數(shù)字驗(yàn)證碼 /// </summary> /// <returns></returns> public FileContentResult NumberVerifyCode() { string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode); byte[] codeImage = VerifyCodeHelper.GetSingleObj().CreateByteByImgVerifyCode(code, 100, 40); return File(codeImage, @"image/jpeg"); } /// <summary> /// 字母驗(yàn)證碼 /// </summary> /// <returns></returns> public FileContentResult 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"); } /// <summary> /// 混合驗(yàn)證碼 /// </summary> /// <returns></returns> public FileContentResult 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.Gif); return File(stream.ToArray(), "image/gif"); } } }
添加頁(yè)面index.cshtml,如下代碼:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <figure> <h4>圖片驗(yàn)證碼</h4> <fieldset> <legend>數(shù)字驗(yàn)證碼</legend> <img id="nubImg" title="數(shù)字驗(yàn)證碼" src="/VerifyCode/NumberVerifyCode?random=" alt="vcode" onclick="refresh()" /> </fieldset> <fieldset> <legend>數(shù)字驗(yàn)證碼</legend> <img id="abcImg" title="字母驗(yàn)證碼" src="/VerifyCode/AbcVerifyCode" alt="vcode" onclick="this.src=this.src+'?'" /> </fieldset> <fieldset> <legend>混合驗(yàn)證碼</legend> <img id="mixImg" title="數(shù)字字母混合驗(yàn)證碼" src="/VerifyCode/MixVerifyCode" alt="vcode" onclick="this.src=this.src+'?'" /> </fieldset> </figure> <script type="text/javascript"> function refresh() { var id = document.getElementById("nubImg"); var str = "/VerifyCode/NumberVerifyCode?random=" + Math.random(); id.setAttribute("src", str); } </script> </body> </html>
生成驗(yàn)證碼如下所示:
關(guān)于“.NET Core 2.0怎樣生成圖片驗(yàn)證碼”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
分享文章:.NETCore2.0怎樣生成圖片驗(yàn)證碼-創(chuàng)新互聯(lián)
轉(zhuǎn)載來源:http://muchs.cn/article16/hoodg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計(jì)、商城網(wǎng)站、App開發(fā)、企業(yè)網(wǎng)站制作、域名注冊(cè)、Google
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容