8

.NET 调整图片尺寸(Resize)各种方法

 3 years ago
source link: http://www.cnblogs.com/stulzq/p/14283068.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文中如无特别说明 .NET 指 .NET 5或者更高版本,代码同样可用于 .NET Core

前言

调整图片尺寸最常用的场景就是 生成缩略图 ,一般为保持纵横比 缩小 ,如果图片 放大 会使图片变得模糊,如果确实有这方面的需求,可以寻找开源的 AI 放大图片的方法。

1.ImageSharp

开源地址: https://github.com/SixLabors/ImageSharp

安装:

dotnet add package SixLabors.ImageSharp

使用:

using var image = Image.Load<Rgba32>("<图片路径>");
image.Mutate(x=>x.Resize(50,0));
image.Save("<保存图片路径>");

其中调用 Resize(width,height) 方法时,如果设置了宽或者高,然后另一个参数设置为 0 ,那么 ImageSharp 将会保持图片纵横比来进行调整大小。

还有更多的设置,比如设置图片质量等,请参阅官方文档: https://docs.sixlabors.com/articles/imagesharp/resize.html

使用此组件,可任意跨平台,无需安装外部依赖

2.ImageProcessor

此组件只能用于 .NET Framework

开源地址: https://github.com/JimBobSquarePants/ImageProcessor

安装:

Install-Package ImageProcessor

添加程序集: System.Drawing

使用:

using (var imageFactory = new ImageFactory(true))
{
    imageFactory.Load("<图片路径>").Resize(new Size(50,50)).Save("<保存图片路径>");
}

3.SkiaSharp

开源地址: https://github.com/mono/SkiaSharp

安装:

dotnet add package SkiaSharp

若在Linux出现依赖问题,可以使用包 SkiaSharp.NativeAssets.Linux.NoDependencies

使用:

var image = SKBitmap.Decode("<图片路径>");
//设置图片新的size
var newImg = image.Resize(new SKSizeI(50, 50), SKFilterQuality.Medium);
using var fs=new FileStream("<保存图片路径>",FileMode.Create);
newImg.Encode(fs,SKEncodedImageFormat.Png, 100);
fs.Flush();

4.NetVips

此组件是基于 C 的库 libvips 来封装的,性能高,资源占用低。并且经过完全测试,跨平台且没有内存泄漏。

开源地址: https://github.com/kleisauke/net-vips

安装:

dotnet add package NetVips
dotnet add package NetVips.Native

两个包都需要安装

使用:

var image = NetVips.Image.NewFromFile("<图片路径>");
var newImg = image.Resize(<图片缩放比例>);
newImg.WriteToFile("<保存图片路径>");

这里的 Resize() 方法设置的是缩放比例,如: 0.5。该组件额外提供了一个生成缩略图的方法 ThumbnailImage() ,可以自定义宽高,如果只穿宽度,那么将保持纵横比。

var image = NetVips.Image.NewFromFile("<图片路径>");
var newImg = image.ThumbnailImage(<图片宽度>);
newImg.WriteToFile("<保存图片路径>");

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK