https://github.com/mono/SkiaSharp
skiasharp
ImageCompression.cs
using SkiaSharp;
namespace ImageCompressStu01
{
///
/// 图片压缩
///
public class ImageCompression
{
///
/// 压缩图片
///
/// 原文件位置
/// 生成目标文件位置
/// 最大宽度,根据此宽度计算是否需要缩放,计算新高度
/// 图片质量,范围0-100
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);
}
}
}
}
}
}
}
Program.cs
namespace ImageCompressStu01
{
internal class Program
{
static void Main(string[] args)
{
string source = "001.jpg";
//实验1 不改变尺寸,图片质量改为80,存为jpg图片
ImageCompression.Compress(source, "target-1.jpg", 1920, 80);
//实验2 不改变尺寸,图片质量改为80,存为png图片
ImageCompression.Compress(source, "target-2.png", 1920, 80);
//实验3 尺寸缩放到宽度800,图片质量改为80,存为jpg图片
ImageCompression.Compress(source, "target-3.jpg", 800, 80);
//实验4 尺寸缩放到宽度800,图片质量改为60,存为jpg图片
ImageCompression.Compress(source, "target-4.jpg", 800, 60);
}
}
}
这个是针对桌面或者控制台项目,web项目处理方式可以参考下面的方法
///
/// 压缩图片
///
/// IFormFile转化为stream
/// 最大宽度,根据此宽度计算是否需要缩放,计算新高度
/// 图片质量,范围0-100
public static byte[]? Compress(Stream file, decimal maxWidth, int quality)
{
byte[]? result = null;
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))
{
result = image.Encode(SKEncodedImageFormat.Jpeg, quality).ToArray();
}
}
}
}
return result;
}
IFormfile转stream方法如下
//内存流
var memory = new MemoryStream();
await formFile.CopyToAsync(memory);
//一定要重置一下,要不然执行压缩会报错
stream.Seek(0, SeekOrigin.Begin);
//文件流
var filePath = "xxxxx.txt";
using (var stream = System.IO.File.Create(filePath))
{
await formFile.CopyToAsync(stream);
}
生成海报的开源库,可以跨平台使用
https://github.com/SixLabors/ImageSharp