From 1be54104cfadf543f116ed1b029fe446ef6919f1 Mon Sep 17 00:00:00 2001 From: Hogen Date: Wed, 23 Nov 2022 18:58:56 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8D=87=E7=BA=A7=E5=88=B0.net=207?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- COMCMS.API/COMCMS.API.csproj | 8 +- COMCMS.Common/COMCMS.Common.csproj | 6 +- COMCMS.Common/ThumbnailHelper.cs | 153 ++++---- COMCMS.Common/VerifyCodeHelper.cs | 48 ++- COMCMS.Common/WatermarkHelper.cs | 206 ++++------- COMCMS.Core/COMCMS.Core.csproj | 4 +- .../AdminCP/Controllers/UploadController.cs | 340 +++++++++--------- COMCMS.Web/COMCMS.Web.csproj | 30 +- Lib.Core/Lib.Core.csproj | 2 +- README.md | 5 +- XCoder/XCoder.csproj | 2 +- 11 files changed, 378 insertions(+), 426 deletions(-) diff --git a/COMCMS.API/COMCMS.API.csproj b/COMCMS.API/COMCMS.API.csproj index 0aff465..0986ee8 100644 --- a/COMCMS.API/COMCMS.API.csproj +++ b/COMCMS.API/COMCMS.API.csproj @@ -1,13 +1,13 @@  - net6.0 + net7.0 - - - + + + diff --git a/COMCMS.Common/COMCMS.Common.csproj b/COMCMS.Common/COMCMS.Common.csproj index b3be7da..fffa700 100644 --- a/COMCMS.Common/COMCMS.Common.csproj +++ b/COMCMS.Common/COMCMS.Common.csproj @@ -1,18 +1,18 @@  - net6.0 + net7.0 - + - + diff --git a/COMCMS.Common/ThumbnailHelper.cs b/COMCMS.Common/ThumbnailHelper.cs index 6a23081..1b5742b 100644 --- a/COMCMS.Common/ThumbnailHelper.cs +++ b/COMCMS.Common/ThumbnailHelper.cs @@ -9,6 +9,10 @@ using System.Text.RegularExpressions; using Microsoft.AspNetCore.Hosting; using System.IO; using NewLife.Log; +using SkiaSharp; +using static System.Net.Mime.MediaTypeNames; +using System.Net.Http; +using System.Security.Policy; namespace COMCMS.Common { @@ -61,7 +65,8 @@ namespace COMCMS.Common /// 生成缩略图的方式 public static void MakeThumbnailImage(string fileName, string newFileName, int width, int height, CutMode mode) { - Image originalImage = Image.FromFile(fileName); + //Image originalImage = Image.FromFile(fileName); + var originalImage = SKBitmap.Decode(fileName); int towidth = width; int toheight = height; @@ -114,91 +119,70 @@ namespace COMCMS.Common break; } - //新建一个bmp图片 - Bitmap b = new Bitmap(towidth, toheight); - try - { - //新建一个画板 - Graphics g = Graphics.FromImage(b); - //设置高质量插值法 - g.InterpolationMode = InterpolationMode.HighQualityBicubic; - //设置高质量,低速度呈现平滑程度 - g.SmoothingMode = SmoothingMode.AntiAlias; - g.PixelOffsetMode = PixelOffsetMode.HighQuality; - //清空画布并以透明背景色填充 - g.Clear(Color.White); - //g.Clear(Color.Transparent); - //在指定位置并且按指定大小绘制原图片的指定部分 - g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); - SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower())); - } - catch (System.Exception e) + var newImg = originalImage.Resize(new SKSizeI(towidth, toheight), SKFilterQuality.Medium); + using var fs = new FileStream(newFileName, FileMode.Create); + //判断类型 + SKEncodedImageFormat imgType = new SKEncodedImageFormat(); + string sFullExtension = Utils.GetFileExtName(fileName).ToLower();//扩展名 + switch (sFullExtension) { - throw e; - } - finally - { - originalImage.Dispose(); - b.Dispose(); + case ".jpg": + case ".jpeg": + imgType = SKEncodedImageFormat.Jpeg; + break; + case ".png": + imgType = SKEncodedImageFormat.Png; + break; + case ".gif": + imgType = SKEncodedImageFormat.Gif; + break; + case ".webp": + imgType = SKEncodedImageFormat.Webp; + break; + case ".bmp": + imgType = SKEncodedImageFormat.Bmp; + break; + default: + imgType = SKEncodedImageFormat.Png; + break; } + newImg.Encode(fs, imgType, 100); + fs.Flush(); + + //新建一个bmp图片 + //Bitmap b = new Bitmap(towidth, toheight); + //try + //{ + // //新建一个画板 + // Graphics g = Graphics.FromImage(b); + // //设置高质量插值法 + // g.InterpolationMode = InterpolationMode.HighQualityBicubic; + // //设置高质量,低速度呈现平滑程度 + // g.SmoothingMode = SmoothingMode.AntiAlias; + // g.PixelOffsetMode = PixelOffsetMode.HighQuality; + // //清空画布并以透明背景色填充 + // g.Clear(Color.White); + // //g.Clear(Color.Transparent); + // //在指定位置并且按指定大小绘制原图片的指定部分 + // g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); + + // SaveImage(b, newFileName, GetCodecInfo("image/" + GetFormat(newFileName).ToString().ToLower())); + //} + //catch (System.Exception e) + //{ + // throw e; + //} + //finally + //{ + // originalImage.Dispose(); + // b.Dispose(); + //} } #endregion #region 帮助方法 - /// - /// 保存图片 - /// - /// Image 对象 - /// 保存路径 - /// 指定格式的编解码参数 - private static void SaveImage(Image image, string savePath, ImageCodecInfo ici) - { - //设置 原图片 对象的 EncoderParameters 对象 - EncoderParameters parameters = new EncoderParameters(1); - parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)100)); - image.Save(savePath, ici, parameters); - parameters.Dispose(); - } - /// - /// 获取图像编码解码器的所有相关信息 - /// - /// 包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串 - /// 返回图像编码解码器的所有相关信息 - private static ImageCodecInfo GetCodecInfo(string mimeType) - { - ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders(); - foreach (ImageCodecInfo ici in CodecInfo) - { - if (ici.MimeType == mimeType) - return ici; - } - return null; - } - /// - /// 得到图片格式 - /// - /// 文件名称 - /// - public static ImageFormat GetFormat(string name) - { - string ext = name.Substring(name.LastIndexOf(".") + 1); - switch (ext.ToLower()) - { - case "jpg": - case "jpeg": - return ImageFormat.Jpeg; - case "bmp": - return ImageFormat.Bmp; - case "png": - return ImageFormat.Png; - case "gif": - return ImageFormat.Gif; - default: - return ImageFormat.Jpeg; - } - } #endregion #region 内容远程保存图片 @@ -212,8 +196,8 @@ namespace COMCMS.Common string recontent = content; if (string.IsNullOrEmpty(content)) return ""; - WebClient client = new WebClient(); - + //WebClient client = new WebClient(); + var _httpClient = new HttpClient(); Regex reg = new Regex("IMG[^>]*?src\\s*=\\s*(?:\"(?<1>[^\"]*)\"|'(?<1>[^\']*)')", RegexOptions.IgnoreCase); MatchCollection m = reg.Matches(content); foreach (Match math in m) @@ -231,7 +215,7 @@ namespace COMCMS.Common else if (imgsrc.EndsWith("jpeg")) ext = "jpeg"; else if (imgsrc.EndsWith("bmp")) ext = "bmp"; string strNewImgName = Utils.GetOrderNum() + "." + ext; - string savepath = $"{_WebRootPath}\\userfiles\\images\\auto\\{DateTime.Now.Year.ToString()}\\{DateTime.Now.ToString("MM")}";// + string savepath = $"{_WebRootPath}{DirectorySeparatorChar}userfiles{DirectorySeparatorChar}images{DirectorySeparatorChar}auto{DirectorySeparatorChar}{DateTime.Now.Year.ToString()}\\{DateTime.Now.ToString("MM")}";// string imgNewSrc = $"/userfiles/images/auto/{DateTime.Now.Year.ToString()}/{DateTime.Now.ToString("MM")}/{strNewImgName}";//保存后路径 //判断路径 if (!Directory.Exists(savepath)) @@ -239,8 +223,13 @@ namespace COMCMS.Common string fullpath = Path.Combine(savepath, strNewImgName);//图片 try { + System.IO.FileStream fs; + byte[] urlContents = _httpClient.GetByteArrayAsync(imgUrl).Result; + fs = new System.IO.FileStream(fullpath, FileMode.CreateNew); + fs.Write(urlContents, 0, urlContents.Length); //保存图片 - client.DownloadFile(imgUrl, fullpath); + //client.DownloadFile(imgUrl, fullpath); + //_httpClient recontent = recontent.Replace(imgUrl, imgNewSrc); } catch (Exception ex) diff --git a/COMCMS.Common/VerifyCodeHelper.cs b/COMCMS.Common/VerifyCodeHelper.cs index c5deb4d..e2bb6e6 100644 --- a/COMCMS.Common/VerifyCodeHelper.cs +++ b/COMCMS.Common/VerifyCodeHelper.cs @@ -8,6 +8,8 @@ using System.IO; using System.Text; using NewLife.Log; using SkiaSharp; +using NewLife.Security; +using static System.Net.Mime.MediaTypeNames; namespace COMCMS.Common { @@ -290,25 +292,44 @@ namespace COMCMS.Common canvas.DrawLine(random.Next(0, width), random.Next(0, height), random.Next(0, width), random.Next(0, height), drawStyle); } + // 在图片上写验证码 + SKPaint textPaint = new SKPaint + { + IsAntialias = true, + TextAlign = SKTextAlign.Left, + Shader = SKShader.CreateLinearGradient(new SKPoint(0, 0), new SKPoint(width, height), new SKColor[] { SKColors.Blue, SKColors.DarkRed }, SKShaderTileMode.Clamp), + TextSize = 22 + }; + canvas.DrawText(text, 4, 24, textPaint); //将文字写到画布上 - using (SKPaint drawStyle = new()) + //using (SKPaint drawStyle = new()) + //{ + // drawStyle.Color = SKColors.Red; + // drawStyle.TextSize = height; + // drawStyle.StrokeWidth = 1; + + // float emHeight = height - (float)height * (float)0.14; + // float emWidth = ((float)width / text.Length) - ((float)width * (float)0.13); + + // canvas.DrawText(text, emWidth, emHeight, drawStyle); + //} + for (int i = 0; i < 5; i++) { - drawStyle.Color = SKColors.Red; - drawStyle.TextSize = height; - drawStyle.StrokeWidth = 1; + canvas.DrawLine(new SKPoint(random.Next(width), random.Next(height)), new SKPoint(random.Next(width), random.Next(height)), new SKPaint() { Color = SKColor.FromHsv(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256)) }); + } - float emHeight = height - (float)height * (float)0.14; - float emWidth = ((float)width / text.Length) - ((float)width * (float)0.13); - - canvas.DrawText(text, emWidth, emHeight, drawStyle); + // 在图片上随机画100个随机颜色点 + for (int i = 0; i < 100; i++) + { + canvas.DrawPoint(new SKPoint(random.Next(width), random.Next(height)), SKColor.FromHsv(random.Next(0, 256), random.Next(0, 256), random.Next(0, 256))); } //画图片的前景噪音点 - for (int i = 0; i < (width * height * 0.6); i++) - { - image.SetPixel(random.Next(0, width), random.Next(0, height), new SKColor(Convert.ToUInt32(random.Next(Int32.MaxValue)))); - } + //for (int i = 0; i < (width * height * 0.6); i++) + //{ + // image.SetPixel(random.Next(0, width), random.Next(0, height), new SKColor(Convert.ToUInt32(random.Next(Int32.MaxValue)))); + //} using var img = SKImage.FromBitmap(image); using SKData p = img.Encode(SKEncodedImageFormat.Png, 100); @@ -335,13 +356,12 @@ namespace COMCMS.Common 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; } diff --git a/COMCMS.Common/WatermarkHelper.cs b/COMCMS.Common/WatermarkHelper.cs index d6546a1..c28f595 100644 --- a/COMCMS.Common/WatermarkHelper.cs +++ b/COMCMS.Common/WatermarkHelper.cs @@ -1,8 +1,11 @@ -using System; +using SkiaSharp; +using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; +using System.IO; using System.Text; +using static System.Net.Mime.MediaTypeNames; namespace COMCMS.Common { @@ -11,51 +14,30 @@ namespace COMCMS.Common /// public class WatermarkHelper { + #region 加图片水印 /// /// 加图片水印 /// + ///

文件名 /// 水印文件名 /// 图片水印位置 - public static void AddImageSignPic(Image img, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) + public static void AddImageSignPic(string copyfullpath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) { - Graphics g = Graphics.FromImage(img); + var img = SKBitmap.Decode(copyfullpath); + using SKCanvas canvas = new(img); + //设置高质量插值法 //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; - System.Drawing.Image watermark = new Bitmap(watermarkFilename); + var watermarkBitmap = SKBitmap.Decode(watermarkFilename); + SKImage watermark = SKImage.FromBitmap(watermarkBitmap); if (watermark.Height >= img.Height || watermark.Width >= img.Width) return; - ImageAttributes imageAttributes = new ImageAttributes(); - ColorMap colorMap = new ColorMap(); - - colorMap.OldColor = Color.FromArgb(255, 0, 255, 0); - colorMap.NewColor = Color.FromArgb(0, 0, 0, 0); - ColorMap[] remapTable = { colorMap }; - - imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); - - float transparency = 0.5F; - if (watermarkTransparency >= 1 && watermarkTransparency <= 10) - transparency = (watermarkTransparency / 10.0F); - - - float[][] colorMatrixElements = { - new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, - new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, - new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, - new float[] {0.0f, 0.0f, 0.0f, transparency, 0.0f}, - new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f} - }; - - ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); - - imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); - int xpos = 0; int ypos = 0; @@ -98,124 +80,74 @@ namespace COMCMS.Common ypos = (int)((img.Height * (float).99) - watermark.Height); break; } - - g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes); - - ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); - ImageCodecInfo ici = null; - foreach (ImageCodecInfo codec in codecs) + SKPoint point = new SKPoint() { - if (codec.MimeType.IndexOf("jpeg") > -1) - ici = codec; + X = xpos, + Y = ypos + }; + + canvas.DrawImage(watermark, point); + + //var newImg = SKImage.fo originalImage.Resize(new SKSizeI(towidth, toheight), SKFilterQuality.Medium); + //canvas. + using var fs = new FileStream(filename, FileMode.Create); + SKEncodedImageFormat imgType = new SKEncodedImageFormat(); + string sFullExtension = Utils.GetFileExtName(filename).ToLower();//扩展名 + switch (sFullExtension) + { + case ".jpg": + case ".jpeg": + imgType = SKEncodedImageFormat.Jpeg; + break; + case ".png": + imgType = SKEncodedImageFormat.Png; + break; + case ".gif": + imgType = SKEncodedImageFormat.Gif; + break; + case ".webp": + imgType = SKEncodedImageFormat.Webp; + break; + case ".bmp": + imgType = SKEncodedImageFormat.Bmp; + break; + default: + imgType = SKEncodedImageFormat.Png; + break; } - EncoderParameters encoderParams = new EncoderParameters(); - long[] qualityParam = new long[1]; - if (quality < 0 || quality > 100) - quality = 80; + img.Encode(fs, imgType, 100); + fs.Flush(); - qualityParam[0] = quality; - EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); - encoderParams.Param[0] = encoderParam; + ////g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes); - if (ici != null) - img.Save(filename, ici, encoderParams); - else - img.Save(filename); + //ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); + //ImageCodecInfo ici = null; + //foreach (ImageCodecInfo codec in codecs) + //{ + // if (codec.MimeType.IndexOf("jpeg") > -1) + // ici = codec; + //} + //EncoderParameters encoderParams = new EncoderParameters(); + //long[] qualityParam = new long[1]; + //if (quality < 0 || quality > 100) + // quality = 80; + + //qualityParam[0] = quality; + + //EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); + //encoderParams.Param[0] = encoderParam; + + //if (ici != null) + // img.Save(filename, ici, encoderParams); + //else + // img.Save(filename); - g.Dispose(); img.Dispose(); watermark.Dispose(); - imageAttributes.Dispose(); } #endregion - #region 增加文字水印 - ///

- /// 增加图片文字水印 - /// - /// 文件名 - /// 水印文字 - /// 图片水印位置 - 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); - SizeF crSize; - crSize = g.MeasureString(watermarkText, drawFont); - - float xpos = 0; - float ypos = 0; - - switch (watermarkStatus) - { - case 1: - xpos = (float)img.Width * (float).01; - ypos = (float)img.Height * (float).01; - break; - case 2: - xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); - ypos = (float)img.Height * (float).01; - break; - case 3: - xpos = ((float)img.Width * (float).99) - crSize.Width; - ypos = (float)img.Height * (float).01; - break; - case 4: - xpos = (float)img.Width * (float).01; - ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); - break; - case 5: - xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); - ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); - break; - case 6: - xpos = ((float)img.Width * (float).99) - crSize.Width; - ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); - break; - case 7: - xpos = (float)img.Width * (float).01; - ypos = ((float)img.Height * (float).99) - crSize.Height; - break; - case 8: - xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); - ypos = ((float)img.Height * (float).99) - crSize.Height; - break; - case 9: - xpos = ((float)img.Width * (float).99) - crSize.Width; - ypos = ((float)img.Height * (float).99) - crSize.Height; - break; - } - - g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1); - g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos); - - ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); - ImageCodecInfo ici = null; - foreach (ImageCodecInfo codec in codecs) - { - if (codec.MimeType.IndexOf("jpeg") > -1) - ici = codec; - } - EncoderParameters encoderParams = new EncoderParameters(); - long[] qualityParam = new long[1]; - if (quality < 0 || quality > 100) - quality = 80; - - qualityParam[0] = quality; - - EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); - encoderParams.Param[0] = encoderParam; - - if (ici != null) - img.Save(filename, ici, encoderParams); - else - img.Save(filename); - - g.Dispose(); - img.Dispose(); - } - #endregion } } diff --git a/COMCMS.Core/COMCMS.Core.csproj b/COMCMS.Core/COMCMS.Core.csproj index 87427cf..0c570f8 100644 --- a/COMCMS.Core/COMCMS.Core.csproj +++ b/COMCMS.Core/COMCMS.Core.csproj @@ -1,11 +1,11 @@  - net6.0 + net7.0 - + diff --git a/COMCMS.Web/Areas/AdminCP/Controllers/UploadController.cs b/COMCMS.Web/Areas/AdminCP/Controllers/UploadController.cs index 05f79fb..4d80269 100644 --- a/COMCMS.Web/Areas/AdminCP/Controllers/UploadController.cs +++ b/COMCMS.Web/Areas/AdminCP/Controllers/UploadController.cs @@ -17,6 +17,7 @@ using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using NewLife.UserGroup.WebUploader; +using SkiaSharp; namespace COMCMS.Web.Areas.AdminCP.Controllers { @@ -81,7 +82,11 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers return Json(errorJson); //return Content(string.Format(tpl, "", callback, "请上传一张图片!"), "text/html"); } - + if (!Utils.IsImgFilename(upload.FileName)) + { + errorJson.error.message = "请选择一张图片!"; + return Json(errorJson); + } var data = Request.Form.Files["upload"]; string filepath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}"; string thumbsFilePath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}_thumbs{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}"; @@ -155,15 +160,15 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers string copyfullpath = fullpath.Replace(sFullExtension, "_copy" + sFullExtension); System.IO.File.Copy(fullpath, copyfullpath); - Image waterpic = new Bitmap(watermarkimg); - Image srcPic = new Bitmap(copyfullpath); + var waterpic = SKBitmap.Decode(watermarkimg); + var srcPic = SKBitmap.Decode(copyfullpath); if (waterpic.Width < srcPic.Width && waterpic.Height < srcPic.Height) { waterpic.Dispose(); //srcPic.Dispose(); try { - WatermarkHelper.AddImageSignPic(srcPic, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity); + WatermarkHelper.AddImageSignPic(copyfullpath, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity); srcPic.Dispose(); System.IO.File.Delete(copyfullpath); } @@ -318,15 +323,15 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers string copyfullpath = fullpath.Replace(sFullExtension, "_copy" + sFullExtension); System.IO.File.Copy(fullpath, copyfullpath); - Image waterpic = new Bitmap(watermarkimg); - Image srcPic = new Bitmap(copyfullpath); + var waterpic = SKBitmap.Decode(watermarkimg); + var srcPic = SKBitmap.Decode(copyfullpath); if (waterpic.Width < srcPic.Width && waterpic.Height < srcPic.Height) { waterpic.Dispose(); //srcPic.Dispose(); try { - WatermarkHelper.AddImageSignPic(srcPic, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity); + WatermarkHelper.AddImageSignPic(copyfullpath, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity); srcPic.Dispose(); System.IO.File.Delete(copyfullpath); } @@ -383,161 +388,161 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers // } //} - #region 二进制上传图片 - /// - /// 二进制上传图片(未实现) - /// - /// - public IActionResult DoWebuploaderImageByBinary() - { - var fileinfo = ""; - var msg = "上传失败!"; - var status = 0; - var name = ""; - var path = ""; - var thumb = ""; - var size = ""; - var ext = ""; - try - { - string upname = Request.Query["name"]; - //判断是否是允许文件扩展名 - string sAllowedExtensions = _attachsetting.ImageAllowedExtensions; - List listAllowedExtensions = new List(); - string[] arrAllowedExtensions = sAllowedExtensions.Split(new string[] { "," }, StringSplitOptions.None); + //#region 二进制上传图片 + ///// + ///// 二进制上传图片(未实现) + ///// + ///// + //public IActionResult DoWebuploaderImageByBinary() + //{ + // var fileinfo = ""; + // var msg = "上传失败!"; + // var status = 0; + // var name = ""; + // var path = ""; + // var thumb = ""; + // var size = ""; + // var ext = ""; + // try + // { + // string upname = Request.Query["name"]; + // //判断是否是允许文件扩展名 + // string sAllowedExtensions = _attachsetting.ImageAllowedExtensions; + // List listAllowedExtensions = new List(); + // string[] arrAllowedExtensions = sAllowedExtensions.Split(new string[] { "," }, StringSplitOptions.None); - string sFileNameNoExt = Utils.GetFileNameWithoutExtension(upname);//文件名字,不带扩展名 - string sFullExtension = Utils.GetFileExtName(upname);//扩展名 + // string sFileNameNoExt = Utils.GetFileNameWithoutExtension(upname);//文件名字,不带扩展名 + // string sFullExtension = Utils.GetFileExtName(upname);//扩展名 - if (arrAllowedExtensions != null && arrAllowedExtensions.Length > 0) - { - foreach (var s in arrAllowedExtensions) - { - listAllowedExtensions.Add(s); - } - } - if (listAllowedExtensions.Find(x => x == sFullExtension.ToLower().Replace(".", "")) == null) - { - return Json(new { status = status, msg = $"{sFullExtension}的文件类型,不允许上传,请上传一张图片!", name = name, path = path, thumb = thumb, size = size, ext = ext }); - } - var req = HttpContext.Request; - var f = Request.Form.Files[0]; + // if (arrAllowedExtensions != null && arrAllowedExtensions.Length > 0) + // { + // foreach (var s in arrAllowedExtensions) + // { + // listAllowedExtensions.Add(s); + // } + // } + // if (listAllowedExtensions.Find(x => x == sFullExtension.ToLower().Replace(".", "")) == null) + // { + // return Json(new { status = status, msg = $"{sFullExtension}的文件类型,不允许上传,请上传一张图片!", name = name, path = path, thumb = thumb, size = size, ext = ext }); + // } + // var req = HttpContext.Request; + // var f = Request.Form.Files[0]; - //Request.EnableRewind(); - Image image = null; - using (StreamReader reader = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true)) - { - var bytes = ConvertToBinary(reader.BaseStream); - image = ReturnPic(bytes); - size = bytes.Length.ToString(); - } + // //Request.EnableRewind(); + // Image image = null; + // using (StreamReader reader = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true)) + // { + // var bytes = ConvertToBinary(reader.BaseStream); + // image = ReturnPic(bytes); + // size = bytes.Length.ToString(); + // } - string filepath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}"; - string thumbsFilePath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}_thumbs{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}"; - //根据附件配置,设置上传图片目录 - string imgPath = DateTime.Now.Year.ToString();//默认按年 - switch (attach.SaveType) - { - case 1://按月份 - imgPath = $"{DateTime.Now.Year.ToString()}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("MM")}"; - break; - case 2: - imgPath = $"{DateTime.Now.Year.ToString()}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("MM")}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("dd")}"; - break; - } - filepath += imgPath;//存放路径 - thumbsFilePath += imgPath;//缩略图路径 - //图片名字 - string imgname = Utils.GetOrderNum() + Utils.GetFileExtName(upname); - switch (attach.IsRandomFileName) - { - case 0://不随机 - imgname = upname; - //判断是否存在 - if (System.IO.File.Exists(Path.Combine(filepath, imgname))) - { - imgname = sFileNameNoExt + "(1)" + sFullExtension; - } - break; - case 1://随机字符串 - imgname = Utils.GetShortGUId() + sFullExtension; - break; - case 2://时间 - imgname = Utils.GetOrderNum() + sFullExtension; - break; - } - string fullpath = Path.Combine(filepath, imgname);//图片 - string fullThumbPath = Path.Combine(thumbsFilePath, imgname);//缩略图 + // string filepath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}"; + // string thumbsFilePath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}_thumbs{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}"; + // //根据附件配置,设置上传图片目录 + // string imgPath = DateTime.Now.Year.ToString();//默认按年 + // switch (attach.SaveType) + // { + // case 1://按月份 + // imgPath = $"{DateTime.Now.Year.ToString()}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("MM")}"; + // break; + // case 2: + // imgPath = $"{DateTime.Now.Year.ToString()}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("MM")}{Path.DirectorySeparatorChar}{DateTime.Now.ToString("dd")}"; + // break; + // } + // filepath += imgPath;//存放路径 + // thumbsFilePath += imgPath;//缩略图路径 + // //图片名字 + // string imgname = Utils.GetOrderNum() + Utils.GetFileExtName(upname); + // switch (attach.IsRandomFileName) + // { + // case 0://不随机 + // imgname = upname; + // //判断是否存在 + // if (System.IO.File.Exists(Path.Combine(filepath, imgname))) + // { + // imgname = sFileNameNoExt + "(1)" + sFullExtension; + // } + // break; + // case 1://随机字符串 + // imgname = Utils.GetShortGUId() + sFullExtension; + // break; + // case 2://时间 + // imgname = Utils.GetOrderNum() + sFullExtension; + // break; + // } + // string fullpath = Path.Combine(filepath, imgname);//图片 + // string fullThumbPath = Path.Combine(thumbsFilePath, imgname);//缩略图 - //判断路径 - if (!Directory.Exists(filepath)) - Directory.CreateDirectory(filepath); - //缩略图路径 - if (!Directory.Exists(thumbsFilePath)) - Directory.CreateDirectory(thumbsFilePath); + // //判断路径 + // if (!Directory.Exists(filepath)) + // Directory.CreateDirectory(filepath); + // //缩略图路径 + // if (!Directory.Exists(thumbsFilePath)) + // Directory.CreateDirectory(thumbsFilePath); - //保存图片 - image.Save(filepath); - //生成缩略图 - if (attach.IsCreateThum == 1) - { - ThumbnailHelper.MakeThumbnailImage(fullpath, fullThumbPath, attach.ThumMaxWidth, attach.ThumMaxHeight, ThumbnailHelper.CutMode.Cut); - } - //添加水印 - if (attach.IsWaterMark == 1 && !string.IsNullOrEmpty(attach.WaterMarkImg)) - { - string watermarkimg = _env.WebRootPath + attach.WaterMarkImg.Replace("/", Path.DirectorySeparatorChar.ToString()); - if (System.IO.File.Exists(watermarkimg)) - { - //先复制一张图片出来 - string copyfullpath = fullpath.Replace(sFullExtension, "_copy" + sFullExtension); - System.IO.File.Copy(fullpath, copyfullpath); + // //保存图片 + // image.Save(filepath); + // //生成缩略图 + // if (attach.IsCreateThum == 1) + // { + // ThumbnailHelper.MakeThumbnailImage(fullpath, fullThumbPath, attach.ThumMaxWidth, attach.ThumMaxHeight, ThumbnailHelper.CutMode.Cut); + // } + // //添加水印 + // if (attach.IsWaterMark == 1 && !string.IsNullOrEmpty(attach.WaterMarkImg)) + // { + // string watermarkimg = _env.WebRootPath + attach.WaterMarkImg.Replace("/", Path.DirectorySeparatorChar.ToString()); + // if (System.IO.File.Exists(watermarkimg)) + // { + // //先复制一张图片出来 + // string copyfullpath = fullpath.Replace(sFullExtension, "_copy" + sFullExtension); + // System.IO.File.Copy(fullpath, copyfullpath); - Image waterpic = new Bitmap(watermarkimg); - Image srcPic = new Bitmap(copyfullpath); - if (waterpic.Width < srcPic.Width && waterpic.Height < srcPic.Height) - { - waterpic.Dispose(); - //srcPic.Dispose(); - try - { - WatermarkHelper.AddImageSignPic(srcPic, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity); - srcPic.Dispose(); - System.IO.File.Delete(copyfullpath); - } - catch - { - if (System.IO.File.Exists(copyfullpath)) - { - System.IO.File.Delete(copyfullpath); - } - } + // var waterpic = SKBitmap.Decode(watermarkimg); + // var srcPic = SKBitmap.Decode(copyfullpath); + // if (waterpic.Width < srcPic.Width && waterpic.Height < srcPic.Height) + // { + // waterpic.Dispose(); + // //srcPic.Dispose(); + // try + // { + // WatermarkHelper.AddImageSignPic(copyfullpath, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity); + // srcPic.Dispose(); + // System.IO.File.Delete(copyfullpath); + // } + // catch + // { + // if (System.IO.File.Exists(copyfullpath)) + // { + // System.IO.File.Delete(copyfullpath); + // } + // } - } - else - { - waterpic.Dispose(); - srcPic.Dispose(); - } - } - } - image.Dispose(); - status = 1; - name = imgname; - path = $"/{attach.AttachPatch}/images/{imgPath.Replace("\\", "/")}/" + imgname; - thumb = $"/{attach.AttachPatch}/_thumbs/images/{imgPath.Replace("\\", "/")}/" + imgname; - ext = sFullExtension; - fileinfo = $"/{attach.AttachPatch}/images/{imgPath.Replace("\\", "/")}/" + imgname; - msg = "上传成功!"; - } - catch (Exception ex) - { - msg = ex.Message; - } + // } + // else + // { + // waterpic.Dispose(); + // srcPic.Dispose(); + // } + // } + // } + // image.Dispose(); + // status = 1; + // name = imgname; + // path = $"/{attach.AttachPatch}/images/{imgPath.Replace("\\", "/")}/" + imgname; + // thumb = $"/{attach.AttachPatch}/_thumbs/images/{imgPath.Replace("\\", "/")}/" + imgname; + // ext = sFullExtension; + // fileinfo = $"/{attach.AttachPatch}/images/{imgPath.Replace("\\", "/")}/" + imgname; + // msg = "上传成功!"; + // } + // catch (Exception ex) + // { + // msg = ex.Message; + // } - return Json(new { status = status, msg = msg, name = name, path = path, thumb = thumb, size = size, ext = ext }); - } - #endregion + // return Json(new { status = status, msg = msg, name = name, path = path, thumb = thumb, size = size, ext = ext }); + //} + //#endregion /// /// 上传图片 @@ -562,6 +567,11 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers msg = "只能上传一张图片格式文件!"; return Content(JsonConvert.SerializeObject(new { status = status, msg = msg, name = name, path = path, thumb = thumb, size = size, ext = ext }), "text/plain"); } + if (!Utils.IsImgFilename(data.FileName)) + { + msg = "只能上传一张图片格式文件!"; + return Content(JsonConvert.SerializeObject(new { status = status, msg = msg, name = name, path = path, thumb = thumb, size = size, ext = ext }), "text/plain"); + } string filepath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}"; string thumbsFilePath = $"{_env.WebRootPath}{Path.DirectorySeparatorChar}{attach.AttachPatch}{Path.DirectorySeparatorChar}_thumbs{Path.DirectorySeparatorChar}images{Path.DirectorySeparatorChar}"; //根据附件配置,设置上传图片目录 @@ -635,15 +645,15 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers string copyfullpath = fullpath.Replace(sFullExtension, "_copy" + sFullExtension); System.IO.File.Copy(fullpath, copyfullpath); - Image waterpic = new Bitmap(watermarkimg); - Image srcPic = new Bitmap(copyfullpath); + var waterpic = SKBitmap.Decode(watermarkimg); + var srcPic = SKBitmap.Decode(copyfullpath); if (waterpic.Width < srcPic.Width && waterpic.Height < srcPic.Height) { waterpic.Dispose(); //srcPic.Dispose(); try { - WatermarkHelper.AddImageSignPic(srcPic, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity); + WatermarkHelper.AddImageSignPic(copyfullpath, fullpath, watermarkimg, attach.WaterMarkPlace, attach.WaterMarkQty, attach.WaterMarkDiaphaneity); srcPic.Dispose(); System.IO.File.Delete(copyfullpath); } @@ -839,7 +849,7 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers var tempDir = "UploadTemp"; var targetDir = "UploadFile"; - var (res,msg) = tempDir.Merge(targetDir, fileName, md5, chunks); + var (res, msg) = tempDir.Merge(targetDir, fileName, md5, chunks); if (!res) { @@ -849,7 +859,7 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers Result = false }); } - + return Json(new { Data = new { md5 = md5, url = Path.Combine("/", targetDir, fileName) }, @@ -886,7 +896,7 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers return Json(new { - Data = fileName!=null && exists ? (object)new { md5 = md5, url = Path.Combine("/", targetDir, fileName) } : null, + Data = fileName != null && exists ? (object)new { md5 = md5, url = Path.Combine("/", targetDir, fileName) } : null, Result = exists }); } @@ -908,12 +918,12 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers /// /// /// - public Image ReturnPic(byte[] streamByte) - { - MemoryStream ms = new MemoryStream(streamByte); - Image img = Image.FromStream(ms); - return img; - } + //public Image ReturnPic(byte[] streamByte) + //{ + // MemoryStream ms = new MemoryStream(streamByte); + // Image img = Image.FromStream(ms); + // return img; + //} #endregion } } \ No newline at end of file diff --git a/COMCMS.Web/COMCMS.Web.csproj b/COMCMS.Web/COMCMS.Web.csproj index a478b92..182efcc 100644 --- a/COMCMS.Web/COMCMS.Web.csproj +++ b/COMCMS.Web/COMCMS.Web.csproj @@ -1,28 +1,28 @@  - net6.0 + net7.0 Linux - - - - + + + + - - - - + + + + - - - + + + - - - + + + diff --git a/Lib.Core/Lib.Core.csproj b/Lib.Core/Lib.Core.csproj index c8eb988..f934fe9 100644 --- a/Lib.Core/Lib.Core.csproj +++ b/Lib.Core/Lib.Core.csproj @@ -1,7 +1,7 @@ - net6.0 + net7.0 diff --git a/README.md b/README.md index f9b9f37..6d02615 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,7 @@ COMCMS NETCORE版本,一个简单的CMS后台管理系统,带前台演示。 ### 更新日志 +- 2022-11-23 升级到.net 7 和使用SkiaSharp 替换掉System.Drawing - 2021-02-02 升级组件,删除ZKWeb组件,增加文章Tag标签 - 2020-12-02 升级到.net5;增加文章栏目、商品分类快速修改排序;增加jwt授权登录 - 2020-11-11 管理组管理增加控制普通管理组的文章和商品权限,文章、商品操作增加权限判断 @@ -14,7 +15,7 @@ COMCMS NETCORE版本,一个简单的CMS后台管理系统,带前台演示。 ### 技术简要 -- .net 5 (请注意升级本地SDK 或者runtime) +- .net 7 (请注意升级本地SDK 或者runtime) - 数据库:Mysql 5.7 /Mysql 8.0 / SqlServer 2008+ - ORM:数据库操作使用XCode,目前支持mysql、sqlserver。详细见:https://github.com/NewLifeX/X - 据库驱动使用:MySQL官方驱动,8.0.23 @@ -29,7 +30,7 @@ COMCMS NETCORE版本,一个简单的CMS后台管理系统,带前台演示。 - COMCMS.Core 数据库操作核心业务逻辑和实体 采用XCode -- COMCMS.Web .net 5 的MVC网站。 +- COMCMS.Web .net 7 的MVC网站。 - XCoder 代码生成器,跟上述的没任何关系,只是为了生成数据库操作业务逻辑和实体而已。 diff --git a/XCoder/XCoder.csproj b/XCoder/XCoder.csproj index d400881..36163ac 100644 --- a/XCoder/XCoder.csproj +++ b/XCoder/XCoder.csproj @@ -1,7 +1,7 @@  - net6.0 + net7.0 enable enable