示例代码:https://download.csdn.net/download/hefeng_aspnet/90294127
在当今的数字时代,图像是 Web 应用程序和用户体验不可或缺的一部分。但是,处理大型图像文件可能会导致网页加载缓慢和更高的存储费用。为了解决这个问题,在保持图像质量的同时压缩和缩小上传图像的大小至关重要。在本文中,我们将探讨如何在 ASP.NET Core 应用程序中使用 ImageSharp 库来实现这一点。
先决条件
在深入研究解决方案之前,请确保您已满足以下条件:
1、安装了 ASP.NET Core 开发工具的 Visual Studio 或 Visual Studio Code。
.NET 核心 SDK。
2、ASP.NET Core 和 C# 的基本知识。
3、在 ASP.NET Core 中压缩并减少图像文件大小
首先,创建一个新的 ASP.NET Core Web API 应用程序或使用现有的应用程序。为了进行演示,我们将创建一个名为“ImageUploadWithCompress”的应用程序。
步骤 1.安装 ImageSharp 库
我们将使用 ImageSharp 库来执行图像压缩。要安装它,请打开项目的终端并运行以下命令:Install-Package SixLabors.ImageSharp
步骤 2. 创建图像压缩服务
在您的项目中,创建一个服务类来处理图像压缩。以下是一个示例服务类:
using SixLabors.ImageSharp.Formats.Jpeg;
namespace ImageUploadWithCompress
{
public class ImageService
{
public async Task CompressAndSaveImageAsync(IFormFile imageFile, string outputPath, int quality = 75)
{
using var imageStream = imageFile.OpenReadStream();
using var image = Image.Load(imageStream);
var encoder = new JpegEncoder
{
Quality = quality, // Adjust this value for desired compression quality
};
await Task.Run(() => image.Save(outputPath, encoder));
}
}
}
上述方法负责压缩以表示的图像IFormFile并异步将压缩后的图像保存到指定的输出路径。
(IFormFile imageFile, string outputPath, int quality = 75):这些是该方法的参数。
1、IFormFile imageFile:此参数表示需要压缩的输入图像文件。IFormFile通常用于处理 Web 应用程序中的文件上传。
2、string outputPath:此参数指定压缩图像的保存路径。
3、int quality = 75:这是一个可选参数,默认值为 75。它决定了 JPEG 压缩的质量。您可以调整此值来控制压缩级别(值越高,质量越好,但文件大小越大;值越低,压缩程度越高,但质量越低)。
步骤3.压缩并保存上传的图像
现在创建一个名为“ImageController”的控制器,用于处理文件上传,使用 ImageService 类压缩并保存上传的图像,同时保持原始文件完好无损。以下是示例:
using Microsoft.AspNetCore.Mvc;
namespace ImageUploadWithCompress.Controllers
{
[Route("api/images")]
[ApiController]
public class ImageController : ControllerBase
{
public ImageController()
{
}
[HttpPost("upload")]
public async Task<IActionResult> UploadImage(IFormFile imageFile)
{
if (imageFile == null || imageFile.Length == 0)
{
// Handle invalid input
return BadRequest("No file uploaded");
}
// Save the orginal file to compress
var outputPath = Path.Combine("uploads", imageFile.FileName);
var imageService = new ImageService();
await imageService.CompressAndSaveImageAsync(imageFile, outputPath, 30);
// We can save the original file as well if needed
var originalFilePath = Path.Combine("uploads", "original_" + imageFile.FileName);
using (var fileStream = new FileStream(originalFilePath, FileMode.Create))
{
await imageFile.CopyToAsync(fileStream);
}
// Return success response or perform further actions
return Ok("Image uploaded and compressed.");
}
}
}
通过遵循这些步骤,您可以有效地减少 ASP.NET Core 应用程序中上传图像的文件大小,而无需使用 zip 文件。图像压缩不仅可以节省存储空间,还可以通过减少图像的加载时间来提高 Web 应用程序的性能。
如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。