升级到.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
+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
}
}