有没有免费可靠的方法来压缩图像文件(.jpg/.png)并在 ASP.NET Core 3.1 MVC 中创建缩略图?
我尝试了 Bitmap 的功能,但它们抛出了“此平台不支持 System.Drawing.Common”之类的异常。
ImageSharp是一款高性能、跨平台的图像处理软件 .NET Core 的库。它作为现代替代品 系统.绘图.通用.
支持多种图像格式和优化的性能, 它是处理图像相关任务的绝佳选择 ASP.NET Core 和其他 .NET Core 项目。
通过集成 SixLabors.ImageSharp NuGet 包,您可以 轻松读取、写入、调整大小以及执行其他图像操作 跨平台方式。
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
// Load the image from a file or stream
using (Image image = Image.Load("path/to/your/image.jpg"))
{
// Resize the image to a specific width and height
int newWidth = 300;
int newHeight = 200;
image.Mutate(x => x.Resize(newWidth, newHeight));
// Save the resized image to a file or stream
image.Save("path/to/your/resized_image.jpg");
}
是的,有免费且可靠的方法可以在 ASP.NET Core 中压缩图像文件和创建缩略图,而无需使用 System.Drawing.Common 库,但由于平台限制,ASP.NET Core 不支持该库。您可以使用以下两个流行且广泛使用的库:
ImageSharp(SixLabors.ImageSharp): ImageSharp 是一个跨平台、高性能的 .NET 图像处理库,可在 ASP.NET Core 应用程序中使用。它提供了一组丰富的图像处理功能,包括调整大小、裁剪、压缩等。 要在 ASP.NET Core 3.1 MVC 应用程序中使用 ImageSharp,您需要安装 SixLabors.ImageSharp.Web NuGet 包。
Install-Package SixLabors.ImageSharp.Web
以下是使用 ImageSharp 压缩图像并生成缩略图的示例代码片段:
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
public void ProcessImage(string inputFilePath, string outputFilePath, int maxWidth, int maxHeight)
{
using (var image = Image.Load(inputFilePath))
{
// Resize the image to create a thumbnail
image.Mutate(x => x.Resize(maxWidth, maxHeight));
// Compress the image with the specified quality level (e.g., 70)
var encoder = new SixLabors.ImageSharp.Formats.Jpeg.JpegEncoder { Quality = 70 };
// Save the thumbnail to the output file
image.Save(outputFilePath, encoder);
}
}