c# - 在 .NET CORE MVC 中压缩图像
问题描述
我开发了一个带有图像上传的网络应用程序。用户可以上传各种图像尺寸的各种图像(jpg、png、...)。目前图像大小在 1MB 到 6MB 之间。使用 API 可以读取图像,但存在问题。它非常慢,因为图像的大小太大。
现在我想将图像大小压缩到最大 300KB - 500KB。我尝试了可以调整图像大小的库 SixLabors.ImageSharp。但是图像文件仍然是相同数量的 MB 大。
有人可以为我提供减小图像大小的解决方案吗?
public async Task<IActionResult> UploadImage(IFormFile file)
{
try
{
var uploads = Path.Combine(HostingEnvironment.WebRootPath, "Uploads/Images");
var filePath = "";
if (file.Length > 0)
{
filePath = Path.Combine(uploads, file.FileName);
byte[] result = null;
// memory stream
using (var memoryStream = new MemoryStream())
// filestream
using (var image = Image.Load(file.OpenReadStream())) // IFormFile inputImage
{
//var before = memoryStream.Length; Removed this, assuming you are using for debugging?
var beforeMutations = image.Size();
// dummy resize options
int width = 50;
int height = 100;
IResampler sampler = KnownResamplers.Lanczos3;
bool compand = true;
ResizeMode mode = ResizeMode.Stretch;
// init resize object
var resizeOptions = new ResizeOptions
{
Size = new Size(width, height),
Sampler = sampler,
Compand = compand,
Mode = mode
};
// mutate image
image.Mutate(x => x
.Resize(resizeOptions));
var afterMutations = image.Size();
//Encode here for quality
var encoder = new JpegEncoder()
{
Quality = 5 //Use variable to set between 5-30 based on your requirements
};
//This saves to the memoryStream with encoder
image.Save(memoryStream, encoder);
memoryStream.Position = 0; // The position needs to be reset.
// prepare result to byte[]
result = memoryStream.ToArray();
var after = memoryStream.Length; // kind of not needed.
using(var fileStream = new FileStream(filePath, FileMode.Create))
{
memoryStream.CopyTo(fileStream);
await file.CopyToAsync(fileStream);
}
}
}
return Ok(new
{
location = filePath.Replace(HostingEnvironment.WebRootPath, "").Replace("\\", "/")
});
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
解决方案
推荐阅读
- php - 当 Woocommerce 购物车为空时添加正文类整个站点
- src - Vue 和 img src 没有反应,因为 URL 没有改变(Geoserver getLegendGraphic)
- html - 我如何做到这一点,所以我有 4 行,结果类使用 flexbox 位于顶部?
- javascript - 如何在webgl上渲染具有指定宽度和高度的二维精灵
- javascript - 如何使用 node.js 从 mySQL 读取数据并回传到 HTML?
- android - react native 应用不是最新打包的页面
- c# - Asp.net Core Entity Framework Linq where 查询测试两个布尔值是否相等
- python - ValueError:轴与数组不匹配
- php - 如何使用 edd_store_discount 功能排除下载,以便轻松进行数字下载插件
- amadeus - 企业用户如何将经过测试的自助服务 REST API 移动到生产环境?