登录
注册
开源
企业版
高校版
搜索
帮助中心
使用条款
关于我们
开源
企业版
高校版
私有云
模力方舟
登录
注册
代码拉取完成,页面将自动刷新
开源项目
>
WEB应用开发
>
后台管理框架
&&
捐赠
捐赠前请先登录
取消
前往登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
Watch
不关注
关注所有动态
仅关注版本发行动态
关注但不提醒动态
87
Star
401
Fork
156
大师兄法号随缘
/
Elight.MVC
代码
Issues
16
Pull Requests
0
Wiki
统计
流水线
服务
质量分析
Jenkins for Gitee
腾讯云托管
腾讯云 Serverless
悬镜安全
阿里云 SAE
Codeblitz
SBOM
我知道了,不再自动展开
更新失败,请稍后重试!
移除标识
内容风险标识
本任务被
标识为内容中包含有代码安全 Bug 、隐私泄露等敏感信息,仓库外成员不可访问
net6之后不支持system.drawing了,发给你个我用ImageSharp改造的绘制验证码的,imagesharp支持linux国产化
待办的
#IA7PAS
gselec
创建于
2024-06-24 11:46
using Gs_Class; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; // //using System.Drawing; //using System.Drawing.Imaging; using SixLabors.Fonts; //using SixLabors.ImageSharp.Drawing; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using static System.Net.Mime.MediaTypeNames; using System.Numerics; using SixLabors.ImageSharp.Drawing.Processing; using iPublic; //using log4net; namespace 外围辅助.Pages.SysTools { /// <summary> /// 验证码页面 /// 修改记录: /// 20240601,zch /// </summary> public class VerifyCodeModel : PageModel { public byte[] imageBytes = null; public ILogger logger = null; public VerifyCodeModel(ILogger<VerifyCodeModel> ALogger) { logger = ALogger; } public void OnGet() { string defaultCode = httpTools.getRequestValueFirst(Request, "", "default"); VerifyCoder verify = new VerifyCoder(HttpContext,logger, defaultCode).saveToSession(); imageBytes = verify.getCodeByteArr(); if (logger != null) logger.LogInformation("生成验证码:" + verify.code + ",图片数组长度:" + (imageBytes == null ? "null" : imageBytes.Length)); ////下面这段代码,用iis运行没问题,用linux的kestrel报错:Headers are read-only, response has already started. ///加上这行ContentLength就不报错了 Response.ContentLength = imageBytes.Length; Response.ContentType = "image/gif"; Response.Body.WriteAsync(imageBytes); } } /// <summary> /// 验证码后台接口 /// 修改记录: /// 20240613,zch,从老项目复制过来 /// </summary> [Route("SysTools/[controller]")] [ApiController] public class VerifyCodeApiController : ControllerBase { public ILogger<VerifyCodeApiController> logger = null; public IHostEnvironment env = null; public VerifyCodeApiController(ILogger<VerifyCodeApiController> ALogger, IHostEnvironment AEnv) { logger = ALogger; env = AEnv; } [HttpGet("getVerifyCode")] [ResponseCache(Duration = 0)] public IActionResult getVerifyCode() { byte[] imageBytes = new VerifyCoder(HttpContext, logger) .saveToSession() .getCodeByteArr(); return File(imageBytes, "image/gif"); } } #region //VerifyCoder,验证码 /// <summary> /// 验证码,海宏软件,20130608,用法: /// 1:发布到controller: /// [HttpGet] /// [ResponseCache(Duration=0)] /// public IActionResult getVerifyCode() /// { /// return File(new VerifyCoder(HttpContext).getNewCodeByteArr(), "image/gif"); /// } /// 2:页面引用: /// <img src="/SysTools/getVerifyCode" onclick="this.src='../SysTools/getVerifyCode?_t='+Date.now().toString()" /> /// 3:判断验证:取Session["VerifyCode"]与输入框比对 /// </summary> public partial class VerifyCoder //: System.Web.UI.Page { public string defaultCode = ""; public string code = ""; public HttpContext httpContext = null; public ILogger logger = null; public string fontPath = ""; private static Color BackColor = Color.White; public int Width = 80; //52、100、75、 public int Height = 20; //21、30、20、 public int fontSize = 24; //12、32、24、 public VerifyCoder(HttpContext AHttpContext, ILogger ALogger = null, string ACode = "") { httpContext = AHttpContext; logger = ALogger; if (_random == null) _random = new Random(); // if (!string.IsNullOrEmpty(ACode)) code = defaultCode = ACode.Trim(); else code = GetRandomCode(); if (logger != null) logger.LogInformation(GetType() + "-初始化code:" + code); this.SetPageNoCache(); } public VerifyCoder refreshCode() { code = defaultCode = GetRandomCode(); if (logger != null) logger.LogInformation(GetType() + "-refreshCode:刷新code:" + defaultCode); return this; } //public Image<Rgba32> getNewCodeImage() //{ // Image<Rgba32> bitmap = null; // try // { // if (_random == null) _random = new Random(); // //生成码,默认码 // if (string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(defaultCode)) code = defaultCode; else code = GetRandomCode(); // if (logger != null) logger.LogInformation(GetType() + "-getNewCodeImage:当前code:" + code + ",准备获取图片"); // //// TODO : use Session["code"] save the VerifyCode // //httpContext.Session.Set("VerifyCode", System.Text.ASCIIEncoding.Default.GetBytes(this.code)); // bitmap = this.getCodeImage(); // } // catch (Exception x) // { // if (logger != null) logger.LogError(x, GetType() + "-getNewCodeImage:" + x.Message); // } // return bitmap; //} public VerifyCoder saveToSession(ISession ASession = null) { var Session = ASession; try { if (Session == null && httpContext != null) Session = httpContext.Session; if (logger != null) logger.LogInformation(GetType() + "-saveToSession:" + code + ",SessionID:" + (Session == null ? "null" : Session.Id)); Session.SetString("VerifyCode", code); } catch (Exception x) { if (logger != null) logger.LogError(x, GetType() + "-saveToSession:" + x.Message); } return this; } public byte[] getCodeByteArr() { byte[] arr = null; Image<Rgba32> bmp = null; MemoryStream ms = null; try { if (logger != null) logger.LogInformation(GetType() + "-getNewCodeByteArr:1当前code:" + code + ",准备获取图片"); bmp = getCodeImage(); //流 ms = new MemoryStream(); if (logger != null) logger.LogInformation(GetType() + "-getNewCodeByteArr:2当前code:" + code + ",准备存图片入流.bmp尺寸:" + (bmp == null ? "null" : bmp.Size)); //bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //Jpeg bmp.SaveAsGif(ms); if (logger != null) logger.LogInformation(GetType() + "-getNewCodeByteArr:3当前code:" + code + ",准备存流入byte[]数组.Stream尺寸:" + (ms == null ? "null" : ms.Length)); arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); if (logger != null) logger.LogInformation(GetType() + "-getNewCodeByteArr:4当前code:" + code + ",已写入byte[]数组.尺寸:" + (arr == null ? "null" : arr.Length)); } catch (Exception x) { } finally { if (ms != null) ms.Close(); } return arr; } /// <summary> /// 绘画事件 /// </summary> public Image<Rgba32> getCodeImage() { Image<Rgba32> image = null; SixLabors.ImageSharp.Color[] color = { SixLabors.ImageSharp.Color.Black, SixLabors.ImageSharp.Color.Red, SixLabors.ImageSharp.Color.Blue, SixLabors.ImageSharp.Color.Green, SixLabors.ImageSharp.Color.Orange, SixLabors.ImageSharp.Color.Brown, SixLabors.ImageSharp.Color.DarkBlue }; //string[] font = { "Times New Roman" }; string s = "", sDir = fontPath, sClass = "getCodeImage"; //需要将字体放到项目中 string[] fonts = { "Arial.ttf" }; char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' }; Random rnd = new Random(); ////生成验证码字符串 //string code = string.Empty; //for (int i = 0; i < 4; i++) code += character[rnd.Next(character.Length)]; //写入Session用于验证码校验,可以对校验码进行加密,提高安全性 //System.Web.HttpContext.Current.Session["verifyCode"] = chkCode; try { //创建画布 image = new Image<Rgba32>(Width, Height); image.Mutate(x => x.BackgroundColor(SixLabors.ImageSharp.Color.White)); //Bitmap bmp = new Bitmap(codeW, codeH - 3); if (logger != null) logger.LogInformation(sClass + "-1创建画布:" + Width + "*" + Height); //Graphics g = Graphics.FromImage(bmp); //填充背景颜色为白色 //g.Clear(Color.White); //画噪线 for (int i = 0; i < 3; i++) { int x1 = rnd.Next(Width); int y1 = rnd.Next(Height); int x2 = rnd.Next(Width); int y2 = rnd.Next(Height); if (logger != null) logger.LogInformation(sClass + "-2画躁线:" + x1 + "," + y1 + "," + x2 + "," + y2); image.Mutate(x => //画实线 x.DrawLine( color[rnd.Next(color.Length)], //字体颜色 1, //字体大小 new SixLabors.ImageSharp.PointF[]{ new Vector2(x1, y1), new Vector2(x2, y2) } //两点一线坐标 )); //Color clr = color[rnd.Next(color.Length)]; //g.DrawLine(new Pen(clr), x1, y1, x2, y2); } //string bPath = $"{Directory.GetCurrentDirectory()}font/"; //string bPath = "C:\\Windows\\Fonts"; //var bPath = Environment.CurrentDirectory; //var install_Family = fontTmp.Add($"font/ARIAL.TTF"); //var install_Family = fontTmp.Add($"ARIAL.TTF"); //var install_Family = fontTmp.Add($"C:/Windows/Fonts/ARIAL.TTF"); //var install_Family = fontTmp.Add($"C:/Windows/Fonts/Arial/ARIAL.TTF"); //字库路径 if (string.IsNullOrEmpty(sDir) || !Directory.Exists(sDir)) { showInfo(sClass + "-3:准备查找字库路径,当前路径:" + Environment.CurrentDirectory); showInfo(sDir = iDefine.findSysDirectory("SysData", s = Environment.CurrentDirectory)); if (Directory.Exists(sDir)) showInfo(sDir = Path.Combine(Path.GetDirectoryName(sDir), "wwwroot", "css", "font")); if (!Directory.Exists(sDir)) { showInfo(sDir = Path.Combine(Path.GetDirectoryName(s), "主程序", "SysData")); if (Directory.Exists(sDir)) showInfo(sDir = Path.Combine(Path.GetDirectoryName(sDir), "wwwroot", "css", "font")); } } if (logger != null) logger.LogInformation(sClass + "-3字库路径:" + sDir); //画验证码 for (int i = 0; i < code.Length; i++) { string fnt = fonts[rnd.Next(fonts.Length)]; ////var install_Family = new FontCollection().Add(System.IO.Path.Combine(bPath, fnt)); var fontTmp = new FontCollection(); //var bPath = Environment.CurrentDirectory; //var install_Family = fontTmp.Add($"font/ARIAL.TTF"); //var install_Family = fontTmp.Add($"ARIAL.TTF"); var install_Family = fontTmp.Add(s = Path.Combine(sDir, "Arial.ttf")); if (logger != null) logger.LogInformation(" 4." + i + "-字库文件:" + s); //var install_Family = fontTmp.Add($"C:/Windows/Fonts/ARIAL.TTF"); //var install_Family = fontTmp.Add($"C:/Windows/Fonts/Arial/ARIAL.TTF"); var font = new SixLabors.Fonts.Font(install_Family, fontSize, FontStyle.Bold); if (logger != null) logger.LogInformation(" 4." + i + "-绘制文字:" + code[i]); image.Mutate(x => x .DrawText( code[i].ToString(), //文字内容 font, color[rnd.Next(color.Length)], new Vector2((float)i * Width / (code.Length), (float)0)) //new Vector2((float)i * 20, (float)0)) ); //将文字写到画布上 //Font ft = new Font(fnt, fontSize); // Color clr = color[rnd.Next(color.Length)]; // g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0); } //画图片的前景噪音点 if (logger != null) logger.LogInformation(sClass + "-5绘制前景噪点." + ""); for (int i = 0; i < 15; i++) { int x1 = rnd.Next(Width); int y1 = rnd.Next(Height); int x2 = x1 + 2; int y2 = y1 + 2; image.Mutate(x => x.DrawLine( //画实线 color[rnd.Next(color.Length)], //字体颜色 2, //字体大小 new SixLabors.ImageSharp.PointF[]{ new Vector2(x1, y1), new Vector2(x2, y2) } //两点一线坐标 )); } //SixLabors.ImageSharp.Formats.Png.PngTextData //IImageFormat bFormat = new Formats; //ImgStr = image.ToBase64String(SixLabors.ImageSharp.Formats.Png.PngFormat.Instance); //image.SaveAsJpeg($"./img/test.jpg"); //System.Drawing.Image bImg = System.Drawing.Image.FromFile($"./img/test.jpg"); } catch (Exception x) { string aMsg = x.Message; if (logger != null) logger.LogError(x, sClass + ":" + x.Message + "\r\n" + x.StackTrace); } return image; Image<Rgba32> g = null, objBitmap = null; try { //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-1:当前code:" + code + ",准备生成图片,尺寸:" + Width + "*" + Height); //objBitmap = new Image<Rgba32>(Width, Height); //g = Graphics.FromImage(objBitmap); //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-2-背景:当前code:" + code); //Paint_Background(g); //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-3-文字:当前code:" + code); //Paint_Text(g); //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-4-噪音点-TextStain:当前code:" + code); //Paint_TextStain(objBitmap); //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-5-Border:当前code:" + code); //Paint_Border(g); } catch (Exception x) { if (logger != null) logger.LogError(x, GetType() + "-getCodeImage:当前code:" + this.code + "," + x.Message); } finally { //if (null != objBitmap) objBitmap.Dispose(); if (null != g) g.Dispose(); } return objBitmap; } public void showInfo(string sInfo, bool lTime = true) { if (logger == null) return; logger.LogInformation(sInfo); } private Random _random = null; private int _brushNameIndex; static string[] FontItems = new string[]{ "Arial", "Helvetica", "Geneva", "sans-serif", "Verdana" }; //static Brush[] BrushItems = new Brush[] { Brushes.OliveDrab, // Brushes.ForestGreen, // Brushes.DarkCyan, // Brushes.LightSlateGray, // Brushes.RoyalBlue, // Brushes.SlateBlue, // Brushes.DarkViolet, // Brushes.MediumVioletRed, // Brushes.IndianRed, // Brushes.Firebrick, // Brushes.Chocolate, // Brushes.Peru, // Brushes.Goldenrod //}; //static string[] BrushName = new string[] { "OliveDrab", // "ForestGreen", // "DarkCyan", // "LightSlateGray", // "RoyalBlue", // "SlateBlue", // "DarkViolet", // "MediumVioletRed", // "IndianRed", // "Firebrick", // "Chocolate", // "Peru", // "Goldenrod" //}; /// <summary> /// 设置页面不被缓存 /// </summary> private void SetPageNoCache() { return; var Response = httpContext.Response; //Response.Buffer = true; //Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1); //Response.Expires = 0; //Response.CacheControl = "no-cache"; Response.Headers.Append("Pragma", "No-Cache"); Response.Headers.Append("Cache-Control", "max-age=0"); //缓存0秒 } /// <summary> /// 取得一个 4 位的随机码 /// </summary> /// <returns></returns> private string GetRandomCode() { string s = code, s2 = Guid.NewGuid().ToString().Substring(0, 4); if (logger != null) logger.LogInformation(GetType() + "-GetRandomCode:刷新" + s + "=>" + s2); return s2; } } #endregion }
using Gs_Class; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; // //using System.Drawing; //using System.Drawing.Imaging; using SixLabors.Fonts; //using SixLabors.ImageSharp.Drawing; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using static System.Net.Mime.MediaTypeNames; using System.Numerics; using SixLabors.ImageSharp.Drawing.Processing; using iPublic; //using log4net; namespace 外围辅助.Pages.SysTools { /// <summary> /// 验证码页面 /// 修改记录: /// 20240601,zch /// </summary> public class VerifyCodeModel : PageModel { public byte[] imageBytes = null; public ILogger logger = null; public VerifyCodeModel(ILogger<VerifyCodeModel> ALogger) { logger = ALogger; } public void OnGet() { string defaultCode = httpTools.getRequestValueFirst(Request, "", "default"); VerifyCoder verify = new VerifyCoder(HttpContext,logger, defaultCode).saveToSession(); imageBytes = verify.getCodeByteArr(); if (logger != null) logger.LogInformation("生成验证码:" + verify.code + ",图片数组长度:" + (imageBytes == null ? "null" : imageBytes.Length)); ////下面这段代码,用iis运行没问题,用linux的kestrel报错:Headers are read-only, response has already started. ///加上这行ContentLength就不报错了 Response.ContentLength = imageBytes.Length; Response.ContentType = "image/gif"; Response.Body.WriteAsync(imageBytes); } } /// <summary> /// 验证码后台接口 /// 修改记录: /// 20240613,zch,从老项目复制过来 /// </summary> [Route("SysTools/[controller]")] [ApiController] public class VerifyCodeApiController : ControllerBase { public ILogger<VerifyCodeApiController> logger = null; public IHostEnvironment env = null; public VerifyCodeApiController(ILogger<VerifyCodeApiController> ALogger, IHostEnvironment AEnv) { logger = ALogger; env = AEnv; } [HttpGet("getVerifyCode")] [ResponseCache(Duration = 0)] public IActionResult getVerifyCode() { byte[] imageBytes = new VerifyCoder(HttpContext, logger) .saveToSession() .getCodeByteArr(); return File(imageBytes, "image/gif"); } } #region //VerifyCoder,验证码 /// <summary> /// 验证码,海宏软件,20130608,用法: /// 1:发布到controller: /// [HttpGet] /// [ResponseCache(Duration=0)] /// public IActionResult getVerifyCode() /// { /// return File(new VerifyCoder(HttpContext).getNewCodeByteArr(), "image/gif"); /// } /// 2:页面引用: /// <img src="/SysTools/getVerifyCode" onclick="this.src='../SysTools/getVerifyCode?_t='+Date.now().toString()" /> /// 3:判断验证:取Session["VerifyCode"]与输入框比对 /// </summary> public partial class VerifyCoder //: System.Web.UI.Page { public string defaultCode = ""; public string code = ""; public HttpContext httpContext = null; public ILogger logger = null; public string fontPath = ""; private static Color BackColor = Color.White; public int Width = 80; //52、100、75、 public int Height = 20; //21、30、20、 public int fontSize = 24; //12、32、24、 public VerifyCoder(HttpContext AHttpContext, ILogger ALogger = null, string ACode = "") { httpContext = AHttpContext; logger = ALogger; if (_random == null) _random = new Random(); // if (!string.IsNullOrEmpty(ACode)) code = defaultCode = ACode.Trim(); else code = GetRandomCode(); if (logger != null) logger.LogInformation(GetType() + "-初始化code:" + code); this.SetPageNoCache(); } public VerifyCoder refreshCode() { code = defaultCode = GetRandomCode(); if (logger != null) logger.LogInformation(GetType() + "-refreshCode:刷新code:" + defaultCode); return this; } //public Image<Rgba32> getNewCodeImage() //{ // Image<Rgba32> bitmap = null; // try // { // if (_random == null) _random = new Random(); // //生成码,默认码 // if (string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(defaultCode)) code = defaultCode; else code = GetRandomCode(); // if (logger != null) logger.LogInformation(GetType() + "-getNewCodeImage:当前code:" + code + ",准备获取图片"); // //// TODO : use Session["code"] save the VerifyCode // //httpContext.Session.Set("VerifyCode", System.Text.ASCIIEncoding.Default.GetBytes(this.code)); // bitmap = this.getCodeImage(); // } // catch (Exception x) // { // if (logger != null) logger.LogError(x, GetType() + "-getNewCodeImage:" + x.Message); // } // return bitmap; //} public VerifyCoder saveToSession(ISession ASession = null) { var Session = ASession; try { if (Session == null && httpContext != null) Session = httpContext.Session; if (logger != null) logger.LogInformation(GetType() + "-saveToSession:" + code + ",SessionID:" + (Session == null ? "null" : Session.Id)); Session.SetString("VerifyCode", code); } catch (Exception x) { if (logger != null) logger.LogError(x, GetType() + "-saveToSession:" + x.Message); } return this; } public byte[] getCodeByteArr() { byte[] arr = null; Image<Rgba32> bmp = null; MemoryStream ms = null; try { if (logger != null) logger.LogInformation(GetType() + "-getNewCodeByteArr:1当前code:" + code + ",准备获取图片"); bmp = getCodeImage(); //流 ms = new MemoryStream(); if (logger != null) logger.LogInformation(GetType() + "-getNewCodeByteArr:2当前code:" + code + ",准备存图片入流.bmp尺寸:" + (bmp == null ? "null" : bmp.Size)); //bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif); //Jpeg bmp.SaveAsGif(ms); if (logger != null) logger.LogInformation(GetType() + "-getNewCodeByteArr:3当前code:" + code + ",准备存流入byte[]数组.Stream尺寸:" + (ms == null ? "null" : ms.Length)); arr = new byte[ms.Length]; ms.Position = 0; ms.Read(arr, 0, (int)ms.Length); if (logger != null) logger.LogInformation(GetType() + "-getNewCodeByteArr:4当前code:" + code + ",已写入byte[]数组.尺寸:" + (arr == null ? "null" : arr.Length)); } catch (Exception x) { } finally { if (ms != null) ms.Close(); } return arr; } /// <summary> /// 绘画事件 /// </summary> public Image<Rgba32> getCodeImage() { Image<Rgba32> image = null; SixLabors.ImageSharp.Color[] color = { SixLabors.ImageSharp.Color.Black, SixLabors.ImageSharp.Color.Red, SixLabors.ImageSharp.Color.Blue, SixLabors.ImageSharp.Color.Green, SixLabors.ImageSharp.Color.Orange, SixLabors.ImageSharp.Color.Brown, SixLabors.ImageSharp.Color.DarkBlue }; //string[] font = { "Times New Roman" }; string s = "", sDir = fontPath, sClass = "getCodeImage"; //需要将字体放到项目中 string[] fonts = { "Arial.ttf" }; char[] character = { '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'd', 'e', 'f', 'h', 'k', 'm', 'n', 'r', 'x', 'y', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' }; Random rnd = new Random(); ////生成验证码字符串 //string code = string.Empty; //for (int i = 0; i < 4; i++) code += character[rnd.Next(character.Length)]; //写入Session用于验证码校验,可以对校验码进行加密,提高安全性 //System.Web.HttpContext.Current.Session["verifyCode"] = chkCode; try { //创建画布 image = new Image<Rgba32>(Width, Height); image.Mutate(x => x.BackgroundColor(SixLabors.ImageSharp.Color.White)); //Bitmap bmp = new Bitmap(codeW, codeH - 3); if (logger != null) logger.LogInformation(sClass + "-1创建画布:" + Width + "*" + Height); //Graphics g = Graphics.FromImage(bmp); //填充背景颜色为白色 //g.Clear(Color.White); //画噪线 for (int i = 0; i < 3; i++) { int x1 = rnd.Next(Width); int y1 = rnd.Next(Height); int x2 = rnd.Next(Width); int y2 = rnd.Next(Height); if (logger != null) logger.LogInformation(sClass + "-2画躁线:" + x1 + "," + y1 + "," + x2 + "," + y2); image.Mutate(x => //画实线 x.DrawLine( color[rnd.Next(color.Length)], //字体颜色 1, //字体大小 new SixLabors.ImageSharp.PointF[]{ new Vector2(x1, y1), new Vector2(x2, y2) } //两点一线坐标 )); //Color clr = color[rnd.Next(color.Length)]; //g.DrawLine(new Pen(clr), x1, y1, x2, y2); } //string bPath = $"{Directory.GetCurrentDirectory()}font/"; //string bPath = "C:\\Windows\\Fonts"; //var bPath = Environment.CurrentDirectory; //var install_Family = fontTmp.Add($"font/ARIAL.TTF"); //var install_Family = fontTmp.Add($"ARIAL.TTF"); //var install_Family = fontTmp.Add($"C:/Windows/Fonts/ARIAL.TTF"); //var install_Family = fontTmp.Add($"C:/Windows/Fonts/Arial/ARIAL.TTF"); //字库路径 if (string.IsNullOrEmpty(sDir) || !Directory.Exists(sDir)) { showInfo(sClass + "-3:准备查找字库路径,当前路径:" + Environment.CurrentDirectory); showInfo(sDir = iDefine.findSysDirectory("SysData", s = Environment.CurrentDirectory)); if (Directory.Exists(sDir)) showInfo(sDir = Path.Combine(Path.GetDirectoryName(sDir), "wwwroot", "css", "font")); if (!Directory.Exists(sDir)) { showInfo(sDir = Path.Combine(Path.GetDirectoryName(s), "主程序", "SysData")); if (Directory.Exists(sDir)) showInfo(sDir = Path.Combine(Path.GetDirectoryName(sDir), "wwwroot", "css", "font")); } } if (logger != null) logger.LogInformation(sClass + "-3字库路径:" + sDir); //画验证码 for (int i = 0; i < code.Length; i++) { string fnt = fonts[rnd.Next(fonts.Length)]; ////var install_Family = new FontCollection().Add(System.IO.Path.Combine(bPath, fnt)); var fontTmp = new FontCollection(); //var bPath = Environment.CurrentDirectory; //var install_Family = fontTmp.Add($"font/ARIAL.TTF"); //var install_Family = fontTmp.Add($"ARIAL.TTF"); var install_Family = fontTmp.Add(s = Path.Combine(sDir, "Arial.ttf")); if (logger != null) logger.LogInformation(" 4." + i + "-字库文件:" + s); //var install_Family = fontTmp.Add($"C:/Windows/Fonts/ARIAL.TTF"); //var install_Family = fontTmp.Add($"C:/Windows/Fonts/Arial/ARIAL.TTF"); var font = new SixLabors.Fonts.Font(install_Family, fontSize, FontStyle.Bold); if (logger != null) logger.LogInformation(" 4." + i + "-绘制文字:" + code[i]); image.Mutate(x => x .DrawText( code[i].ToString(), //文字内容 font, color[rnd.Next(color.Length)], new Vector2((float)i * Width / (code.Length), (float)0)) //new Vector2((float)i * 20, (float)0)) ); //将文字写到画布上 //Font ft = new Font(fnt, fontSize); // Color clr = color[rnd.Next(color.Length)]; // g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 18, (float)0); } //画图片的前景噪音点 if (logger != null) logger.LogInformation(sClass + "-5绘制前景噪点." + ""); for (int i = 0; i < 15; i++) { int x1 = rnd.Next(Width); int y1 = rnd.Next(Height); int x2 = x1 + 2; int y2 = y1 + 2; image.Mutate(x => x.DrawLine( //画实线 color[rnd.Next(color.Length)], //字体颜色 2, //字体大小 new SixLabors.ImageSharp.PointF[]{ new Vector2(x1, y1), new Vector2(x2, y2) } //两点一线坐标 )); } //SixLabors.ImageSharp.Formats.Png.PngTextData //IImageFormat bFormat = new Formats; //ImgStr = image.ToBase64String(SixLabors.ImageSharp.Formats.Png.PngFormat.Instance); //image.SaveAsJpeg($"./img/test.jpg"); //System.Drawing.Image bImg = System.Drawing.Image.FromFile($"./img/test.jpg"); } catch (Exception x) { string aMsg = x.Message; if (logger != null) logger.LogError(x, sClass + ":" + x.Message + "\r\n" + x.StackTrace); } return image; Image<Rgba32> g = null, objBitmap = null; try { //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-1:当前code:" + code + ",准备生成图片,尺寸:" + Width + "*" + Height); //objBitmap = new Image<Rgba32>(Width, Height); //g = Graphics.FromImage(objBitmap); //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-2-背景:当前code:" + code); //Paint_Background(g); //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-3-文字:当前code:" + code); //Paint_Text(g); //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-4-噪音点-TextStain:当前code:" + code); //Paint_TextStain(objBitmap); //if (logger != null) logger.LogInformation(GetType() + "-getCodeImage-5-Border:当前code:" + code); //Paint_Border(g); } catch (Exception x) { if (logger != null) logger.LogError(x, GetType() + "-getCodeImage:当前code:" + this.code + "," + x.Message); } finally { //if (null != objBitmap) objBitmap.Dispose(); if (null != g) g.Dispose(); } return objBitmap; } public void showInfo(string sInfo, bool lTime = true) { if (logger == null) return; logger.LogInformation(sInfo); } private Random _random = null; private int _brushNameIndex; static string[] FontItems = new string[]{ "Arial", "Helvetica", "Geneva", "sans-serif", "Verdana" }; //static Brush[] BrushItems = new Brush[] { Brushes.OliveDrab, // Brushes.ForestGreen, // Brushes.DarkCyan, // Brushes.LightSlateGray, // Brushes.RoyalBlue, // Brushes.SlateBlue, // Brushes.DarkViolet, // Brushes.MediumVioletRed, // Brushes.IndianRed, // Brushes.Firebrick, // Brushes.Chocolate, // Brushes.Peru, // Brushes.Goldenrod //}; //static string[] BrushName = new string[] { "OliveDrab", // "ForestGreen", // "DarkCyan", // "LightSlateGray", // "RoyalBlue", // "SlateBlue", // "DarkViolet", // "MediumVioletRed", // "IndianRed", // "Firebrick", // "Chocolate", // "Peru", // "Goldenrod" //}; /// <summary> /// 设置页面不被缓存 /// </summary> private void SetPageNoCache() { return; var Response = httpContext.Response; //Response.Buffer = true; //Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1); //Response.Expires = 0; //Response.CacheControl = "no-cache"; Response.Headers.Append("Pragma", "No-Cache"); Response.Headers.Append("Cache-Control", "max-age=0"); //缓存0秒 } /// <summary> /// 取得一个 4 位的随机码 /// </summary> /// <returns></returns> private string GetRandomCode() { string s = code, s2 = Guid.NewGuid().ToString().Substring(0, 4); if (logger != null) logger.LogInformation(GetType() + "-GetRandomCode:刷新" + s + "=>" + s2); return s2; } } #endregion }
评论 (
1
)
登录
后才可以发表评论
状态
待办的
待办的
进行中
已完成
已关闭
负责人
未设置
标签
未设置
标签管理
里程碑
未关联里程碑
未关联里程碑
Pull Requests
未关联
未关联
关联的 Pull Requests 被合并后可能会关闭此 issue
分支
未关联
分支 (2)
标签 (1)
master
dev
V1.0.0
开始日期   -   截止日期
-
置顶选项
不置顶
置顶等级:高
置顶等级:中
置顶等级:低
优先级
不指定
严重
主要
次要
不重要
参与者(1)
C#
1
https://gitee.com/zjwno1/Elight.MVC-ASP.NET.git
git@gitee.com:zjwno1/Elight.MVC-ASP.NET.git
zjwno1
Elight.MVC-ASP.NET
Elight.MVC
点此查找更多帮助
搜索帮助
Git 命令在线学习
如何在 Gitee 导入 GitHub 仓库
Git 仓库基础操作
企业版和社区版功能对比
SSH 公钥设置
如何处理代码冲突
仓库体积过大,如何减小?
如何找回被删除的仓库数据
Gitee 产品配额说明
GitHub仓库快速导入Gitee及同步更新
什么是 Release(发行版)
将 PHP 项目自动发布到 packagist.org
评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册