使用SkiaSharp组件实现功能,组件下载在nuget中安装最新版本至项目
功能实现类:
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace YiSha.Util
{
public static class ImageCompression
{
/// <summary>
/// 压缩图片
/// </summary>
/// <param name="source">原文件位置</param>
/// <param name="target">生成目标文件位置</param>
/// <param name="maxWidth">最大宽度,根据此宽度计算是否需要缩放,计算新高度</param>
/// <param name="quality">图片质量,范围0-100</param>
public static void Compress(string source, string target, decimal maxWidth, int quality)
{
using (var file = File.OpenRead(source))
using (var fileStream = new SKManagedStream(file))
using (var bitmap = SKBitmap.Decode(fileStream))
{
var width = (decimal)bitmap.Width;
var height = (decimal)bitmap.Height;
var newWidth = width;
var newHeight = height;
if (width > maxWidth)
{
newWidth = maxWidth;
newHeight = height / width * maxWidth;
}
using (var resized = bitmap.Resize(new SKImageInfo((int)newWidth, (int)newHeight), SKFilterQuality.Medium))
{
if (resized != null)
{
using (var image = SKImage.FromBitmap(resized))
using (var writeStream = File.OpenWrite(target))
{
image.Encode(SKEncodedImageFormat.Jpeg, quality).SaveTo(writeStream);
}
}
}
}
}
}
}
方法调用:
//absoluteFileNameold:需要压缩的文件路径
//absoluteFileNamenew:压缩后文件的保存路径
//1920:图片分辨率
//80:图片质量(0-100,越高越清晰,越小越模糊)
ImageCompression.Compress(absoluteFileNameold, absoluteFileNamenew, 1920, 80);//压缩图片并保存