1、通过NuGet包管理器安装SkiaSharp
/// <summary>
/// 创建图像的缩略图。使用SkiaSharp,以支持跨平台。
/// </summary>
/// <param name="orgPath">原图文件全路径</param>
/// <param name="thuPath">将生成的缩略图文件全路径</param>
public static void MakeThumb(string orgPath, string thuPath)
{
const int width = 180, height = 135;
const int quality = 100; //质量为[SKFilterQuality.Medium]结果的100%
using var input = File.OpenRead(orgPath);
using var inputStream = new SKManagedStream(input);
using var original = SKBitmap.Decode(inputStream);
if (original.Width <= width && original.Height <= height)//如果宽度和高度都小于缩率图值,则直接复制文件
{
File.Copy(orgPath, thuPath);
}
else
{
using (var resized = original.Resize(new SKImageInfo(width, height), SKFilterQuality.Medium))
{
if (resized != null)
{
using var image = SKImage.FromBitmap(resized);
using var output = File.OpenWrite(thuPath);
image.Encode(SKEncodedImageFormat.Png, quality).SaveTo(output);
}
}
}
}