From a9bdec611c72d6cd77f767a4d9ea5204a42690a9 Mon Sep 17 00:00:00 2001 From: "DESKTOP-M4V1LH5\\Jin" Date: Mon, 11 Jan 2021 16:02:17 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=9B=BE=E7=89=87=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- COMCMS.Common/Utils.cs | 6 + COMCMS.Common/VerifyCodeHelper.cs | 295 ++++++++++++++++++ COMCMS.Common/WatermarkHelper.cs | 12 +- .../AdminCP/Controllers/SystemController.cs | 4 +- .../AdminCP/Controllers/UploadController.cs | 2 +- COMCMS.Web/Controllers/HomeController.cs | 5 + .../Controllers/VerifyCodeController.cs | 57 ++++ 7 files changed, 372 insertions(+), 9 deletions(-) create mode 100644 COMCMS.Common/VerifyCodeHelper.cs create mode 100644 COMCMS.Web/Controllers/VerifyCodeController.cs diff --git a/COMCMS.Common/Utils.cs b/COMCMS.Common/Utils.cs index c7a2c35..8df2c2f 100644 --- a/COMCMS.Common/Utils.cs +++ b/COMCMS.Common/Utils.cs @@ -13,6 +13,7 @@ using System.Net.NetworkInformation; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; +using NewLife.Caching; namespace COMCMS.Common { @@ -116,6 +117,11 @@ namespace COMCMS.Common /// Home=99 } + + /// + /// 内存缓存 + /// + public static ICache MemoryCahce { get; set; } = Cache.Default; #endregion #region 验证部分 diff --git a/COMCMS.Common/VerifyCodeHelper.cs b/COMCMS.Common/VerifyCodeHelper.cs new file mode 100644 index 0000000..ec0f10d --- /dev/null +++ b/COMCMS.Common/VerifyCodeHelper.cs @@ -0,0 +1,295 @@ +using NewLife.Caching; +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Drawing2D; +using System.Drawing.Imaging; +using System.IO; +using System.Text; +using NewLife.Log; + +namespace COMCMS.Common +{ + public sealed class VerifyCodeHelper + { + #region 单例模式 + //Session Key + public readonly string SESSION_KEY = "comcms_verifycode"; + //创建私有化静态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 }; + + /// + /// 1.数字验证码 + /// + /// + /// + 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; + } + + /// + /// 2.字母验证码 + /// + /// 字符长度 + /// 验证码字符 + 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); + } + + /// + /// 3.混合验证码 + /// + /// 字符长度 + /// 验证码字符 + 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); + } + + /// + /// 产生验证码(随机产生4-6位) + /// + /// 验证码类型:数字,字符,符合 + /// + 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; + } + + //2019-03-02 增加存入缓存 + //var ic = new MemoryCache(); + //ic.Set("code_" + verifyCode, verifyCode, 120);//2分钟自动过期 + //2019-03-04 增加Redis缓存 + Utils.MemoryCahce.Set("code_" + verifyCode, verifyCode, 120); + + return verifyCode; + } + #endregion + + #region 验证码图片 + /// + /// 验证码图片 => Bitmap + /// + /// 验证码 + /// 宽 + /// 高 + /// Bitmap + 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; + } + + /// + /// 验证码图片 => byte[] + /// + /// 验证码 + /// 宽 + /// 高 + /// byte[] + 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 + + #region 验证验证码 + /// + /// 验证验证码是否成功 + /// + /// + /// + public bool VerifyCodeIsOK(string code) + { + string vc = SessionHelper.GetSession(SESSION_KEY)?.ToString(); + //2019-03-02 增加缓存判断 + if (string.IsNullOrEmpty(vc)) + { + //如果Session为空,则使用缓存判断 + //var ic = new MemoryCache(); + //vc = ic.Get("code_" + code); + //var ic = Utils.RedisCahce;//Redis.Create(Utils.RedisServer, Utils.RedisIndex); + vc = Utils.MemoryCahce.Get("code_" + code);// ic.Get("code_" + code); + //XTrace.WriteLine($"从缓存中获取验证码:code_{code}:{vc}"); + } + + if (!string.IsNullOrEmpty(vc) && !string.IsNullOrEmpty(code)) + { + if (vc.ToUpper() == code.ToUpper()) + return true; + } + + + return false; + } + #endregion + } +} diff --git a/COMCMS.Common/WatermarkHelper.cs b/COMCMS.Common/WatermarkHelper.cs index 21fa9c0..d6546a1 100644 --- a/COMCMS.Common/WatermarkHelper.cs +++ b/COMCMS.Common/WatermarkHelper.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; -using System.DrawingCore; -using System.DrawingCore.Imaging; +using System.Drawing; +using System.Drawing.Imaging; using System.Text; namespace COMCMS.Common @@ -25,7 +25,7 @@ namespace COMCMS.Common //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - System.DrawingCore.Image watermark = new Bitmap(watermarkFilename); + System.Drawing.Image watermark = new Bitmap(watermarkFilename); if (watermark.Height >= img.Height || watermark.Width >= img.Width) return; @@ -115,7 +115,7 @@ namespace COMCMS.Common qualityParam[0] = quality; - EncoderParameter encoderParam = new EncoderParameter(System.DrawingCore.Imaging.Encoder.Quality, qualityParam); + EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) @@ -138,7 +138,7 @@ namespace COMCMS.Common /// 文件名 /// 水印文字 /// 图片水印位置 - public static void AddImageSignText(System.DrawingCore.Image img, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize) + public static void AddImageSignText(Image img, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize) { Graphics g = Graphics.FromImage(img); Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel); @@ -205,7 +205,7 @@ namespace COMCMS.Common qualityParam[0] = quality; - EncoderParameter encoderParam = new EncoderParameter(System.DrawingCore.Imaging.Encoder.Quality, qualityParam); + EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) diff --git a/COMCMS.Web/Areas/AdminCP/Controllers/SystemController.cs b/COMCMS.Web/Areas/AdminCP/Controllers/SystemController.cs index 224fc6b..665e8eb 100644 --- a/COMCMS.Web/Areas/AdminCP/Controllers/SystemController.cs +++ b/COMCMS.Web/Areas/AdminCP/Controllers/SystemController.cs @@ -179,8 +179,8 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers { if (!string.IsNullOrWhiteSpace(model.WaterMarkImg)) { - string imgPath = _env.WebRootPath + model.WaterMarkImg.Replace("/", "\\"); - NewLife.Log.XTrace.WriteLine(_env.WebRootPath + "|" + Path.Combine(_env.WebRootPath, model.WaterMarkImg) + "|" + imgPath); + string imgPath = _env.WebRootPath + model.WaterMarkImg.Replace("/", Path.DirectorySeparatorChar.ToString()); + //NewLife.Log.XTrace.WriteLine(_env.WebRootPath + "|" + Path.Combine(_env.WebRootPath, model.WaterMarkImg) + "|" + imgPath); if (!System.IO.File.Exists(imgPath)) { tip.Message = "水印图片不存在,请重新上传!"; diff --git a/COMCMS.Web/Areas/AdminCP/Controllers/UploadController.cs b/COMCMS.Web/Areas/AdminCP/Controllers/UploadController.cs index f46b309..05f79fb 100644 --- a/COMCMS.Web/Areas/AdminCP/Controllers/UploadController.cs +++ b/COMCMS.Web/Areas/AdminCP/Controllers/UploadController.cs @@ -12,7 +12,7 @@ using COMCMS.Web.Models; using Newtonsoft.Json; using System.IO; using COMCMS.Core.Models; -using System.DrawingCore; +using System.Drawing; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; diff --git a/COMCMS.Web/Controllers/HomeController.cs b/COMCMS.Web/Controllers/HomeController.cs index fe21558..28b40d6 100644 --- a/COMCMS.Web/Controllers/HomeController.cs +++ b/COMCMS.Web/Controllers/HomeController.cs @@ -219,6 +219,11 @@ namespace COMCMS.Web.Controllers // return ac.Index(1); // //return Content(";ath1:" + path1+";path2:"+path2); //} + //[HttpGet] + //public IActionResult Test() + //{ + // return View(); + //} #endregion diff --git a/COMCMS.Web/Controllers/VerifyCodeController.cs b/COMCMS.Web/Controllers/VerifyCodeController.cs new file mode 100644 index 0000000..28278e7 --- /dev/null +++ b/COMCMS.Web/Controllers/VerifyCodeController.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using COMCMS.Common; +using Microsoft.AspNetCore.Mvc; +using NewLife.Caching; +using NewLife.Log; +namespace COMCMS.Web.Controllers +{ + public class VerifyCodeController : Controller + { + /// +         /// 数字验证码 +         /// +         /// + public FileContentResult NumberVerifyCode() + { + string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.NumberVerifyCode); + //写入Session + SessionHelper.WriteSession(VerifyCodeHelper.GetSingleObj().SESSION_KEY, code); + byte[] codeImage = VerifyCodeHelper.GetSingleObj().CreateByteByImgVerifyCode(code, 100, 32); + return File(codeImage, @"image/jpeg"); + } + + /// +         /// 字母验证码 +         /// +         /// + public FileContentResult CharVerifyCode() + { + string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.AbcVerifyCode); + //写入Session + SessionHelper.WriteSession(VerifyCodeHelper.GetSingleObj().SESSION_KEY, code); + var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 32); + MemoryStream stream = new MemoryStream(); + bitmap.Save(stream, ImageFormat.Png); + return File(stream.ToArray(), "image/png"); + } + + /// +         /// 混合验证码 +         /// +         /// + public FileContentResult MixVerifyCode() + { + string code = VerifyCodeHelper.GetSingleObj().CreateVerifyCode(VerifyCodeHelper.VerifyCodeType.MixVerifyCode); + SessionHelper.WriteSession(VerifyCodeHelper.GetSingleObj().SESSION_KEY, code); + var bitmap = VerifyCodeHelper.GetSingleObj().CreateBitmapByImgVerifyCode(code, 100, 32); + MemoryStream stream = new MemoryStream(); + bitmap.Save(stream, ImageFormat.Gif); + return File(stream.ToArray(), "image/gif"); + } + } +} \ No newline at end of file