.net下跨平台图像处理
https://github.com/mono/SkiaSharp
安装包
skiasharp
效果
代码
ImageCompression.cs
using SkiaSharp;
namespace ImageCompressStu01
{
/// <summary>
/// 图片压缩
/// </summary>
public 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);
}
}
}
}
}
}
}
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项目处理方式可以参考下面的方法
/// <summary>
/// 压缩图片
/// </summary>
/// <param name="file">IFormFile转化为stream</param>
/// <param name="maxWidth">最大宽度,根据此宽度计算是否需要缩放,计算新高度</param>
/// <param name="quality">图片质量,范围0-100</param>
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);
//文件流
var filePath = "xxxxx.txt";
using (var stream = System.IO.File.Create(filePath))
{
await formFile.CopyToAsync(stream);
}
参考1
参考2
扩展
生成海报的开源库,可以跨平台使用
https://github.com/SixLabors/ImageSharp