升级到.net 7

This commit is contained in:
2022-11-23 18:58:56 +08:00
parent 23a0c4b32e
commit bcd4bca768
11 changed files with 378 additions and 426 deletions
+4 -4
View File
@@ -1,13 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NewLife.Core" Version="10.0.2022.1001" />
<PackageReference Include="Senparc.Weixin" Version="6.15.5" />
<PackageReference Include="Senparc.Weixin.MP" Version="16.18.7" />
<PackageReference Include="NewLife.Core" Version="10.0.2022.1101" />
<PackageReference Include="Senparc.Weixin" Version="6.15.7" />
<PackageReference Include="Senparc.Weixin.MP" Version="16.18.9" />
</ItemGroup>
<ItemGroup>
+3 -3
View File
@@ -1,18 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="NewLife.Core" Version="10.0.2022.1001" />
<PackageReference Include="NewLife.Core" Version="10.0.2022.1101" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="PinYinConverterCore" Version="1.0.2" />
<PackageReference Include="SkiaSharp" Version="2.88.3" />
<PackageReference Include="SkiaSharp.NativeAssets.Linux" Version="2.88.3" />
<PackageReference Include="SkiaSharp.QrCode" Version="0.6.0" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.1" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="7.0.0" />
</ItemGroup>
</Project>
+71 -82
View File
@@ -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
/// <param name="mode">生成缩略图的方式</param>
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 帮助方法
/// <summary>
/// 保存图片
/// </summary>
/// <param name="image">Image 对象</param>
/// <param name="savePath">保存路径</param>
/// <param name="ici">指定格式的编解码参数</param>
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();
}
/// <summary>
/// 获取图像编码解码器的所有相关信息
/// </summary>
/// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param>
/// <returns>返回图像编码解码器的所有相关信息</returns>
private static ImageCodecInfo GetCodecInfo(string mimeType)
{
ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo ici in CodecInfo)
{
if (ici.MimeType == mimeType)
return ici;
}
return null;
}
/// <summary>
/// 得到图片格式
/// </summary>
/// <param name="name">文件名称</param>
/// <returns></returns>
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)
+34 -14
View File
@@ -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<string>("code_" + code);// ic.Get<string>("code_" + code);
//XTrace.WriteLine($"从缓存中获取验证码:code_{code}:{vc}");
}
if (!string.IsNullOrEmpty(vc) && !string.IsNullOrEmpty(code))
{
if (vc.ToUpper() == code.ToUpper())
return true;
}
return false;
}
+69 -137
View File
@@ -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
/// </summary>
public class WatermarkHelper
{
#region 加图片水印
/// <summary>
/// 加图片水印
/// </summary>
/// <p
/// <param name="filename">文件名</param>
/// <param name="watermarkFilename">水印文件名</param>
/// <param name="watermarkStatus">图片水印位置</param>
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 增加文字水印
/// <summary>
/// 增加图片文字水印
/// </summary>
/// <param name="filename">文件名</param>
/// <param name="watermarkText">水印文字</param>
/// <param name="watermarkStatus">图片水印位置</param>
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
}
}
+2 -2
View File
@@ -1,11 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="NewLife.XCode" Version="11.3.2022.1001" />
<PackageReference Include="NewLife.XCode" Version="11.3.2022.1101" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
</ItemGroup>
@@ -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 二进制上传图片
/// <summary>
/// 二进制上传图片(未实现)
/// </summary>
/// <returns></returns>
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<string> listAllowedExtensions = new List<string>();
string[] arrAllowedExtensions = sAllowedExtensions.Split(new string[] { "," }, StringSplitOptions.None);
//#region 二进制上传图片
///// <summary>
///// 二进制上传图片(未实现)
///// </summary>
///// <returns></returns>
//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<string> listAllowedExtensions = new List<string>();
// 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
/// <summary>
/// 上传图片
@@ -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
/// </summary>
/// <param name="streamByte"></param>
/// <returns></returns>
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
}
}
+15 -15
View File
@@ -1,28 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MailKit" Version="2.15.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.9" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.9" />
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="6.0.9" />
<PackageReference Include="MailKit" Version="3.4.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="7.0.0" />
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="7.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.17.0" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="6.0.10" />
<PackageReference Include="MimeKit" Version="3.4.1" />
<PackageReference Include="MySql.Data" Version="8.0.30" />
<PackageReference Include="NewLife.XCode" Version="11.3.2022.1001" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="7.0.0" />
<PackageReference Include="MimeKit" Version="3.4.2" />
<PackageReference Include="MySql.Data" Version="8.0.31" />
<PackageReference Include="NewLife.XCode" Version="11.3.2022.1101" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Senparc.NeuChar" Version="2.1.1.1" />
<PackageReference Include="Senparc.Weixin" Version="6.15.5" />
<PackageReference Include="Senparc.Weixin.MP" Version="16.18.7" />
<PackageReference Include="Senparc.NeuChar" Version="2.1.2" />
<PackageReference Include="Senparc.Weixin" Version="6.15.7" />
<PackageReference Include="Senparc.Weixin.MP" Version="16.18.9" />
<PackageReference Include="Senparc.Weixin.MP.MvcExtension" Version="4.1.1" />
<PackageReference Include="Senparc.Weixin.TenPay" Version="1.12.2" />
<PackageReference Include="Senparc.Weixin.WxOpen" Version="3.15.7.1" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.3" />
<PackageReference Include="Senparc.Weixin.TenPay" Version="1.12.4" />
<PackageReference Include="Senparc.Weixin.WxOpen" Version="3.15.9" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.5" />
</ItemGroup>
<ItemGroup>
+1 -1
View File
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
+3 -2
View File
@@ -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 代码生成器,跟上述的没任何关系,只是为了生成数据库操作业务逻辑和实体而已。
+1 -1
View File
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>