【发布时间】:2021-05-20 16:03:15
【问题描述】:
在我的大学电子商务画廊项目中,我想在上传图像时自动压缩图像的大小,就像上传后图像大小为 2mb 一样,它会达到 600 kb 或 400kb,那么如何做到这一点..我的代码如下..
ProductController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Upsert(ProductVM productVM)
{
if (ModelState.IsValid)
{
string webRootPath = _hostEnvironment.WebRootPath; //getting image Path
var files = HttpContext.Request.Form.Files; //Retrive all the files that are uploaded
if(files.Count > 0) //that means file was uploaded
{
string fileName = Guid.NewGuid().ToString();
var uploads = Path.Combine(webRootPath, @"images\products");
var extenstion = Path.GetExtension(files[0].FileName);
if (productVM.Product.ImageUrl != null)
{
//this is an edit and we need to remove old image
var imagePath = Path.Combine(webRootPath,
productVM.Product.ImageUrl.TrimStart('\\'));
if (System.IO.File.Exists(imagePath))
{
System.IO.File.Delete(imagePath);
}
}
using (var filesStreams = new FileStream(Path.Combine(uploads, fileName +
extenstion), FileMode.Create))
{
files[0].CopyTo(filesStreams);
}
productVM.Product.ImageUrl = @"\images\products\" + fileName + extenstion;
}
else
{
//update when they do not change the image
if (productVM.Product.Id != 0)
{
Product objFromDb = await _unitOfWork.Product.GetAsync(productVM.Product.Id);
productVM.Product.ImageUrl = objFromDb.ImageUrl;
}
}
if (productVM.Product.Id == 0)
{
await _unitOfWork.Product.AddAsync(productVM.Product);
}
else
{
_unitOfWork.Product.Update(productVM.Product);
}
_unitOfWork.Save();
return RedirectToAction(nameof(Index));
}
..
..
..
return View(productVM);
}
Upsert.cshtml
<section>
<div class="container-lg pt-4">
<form method="post" enctype="multipart/form-data">
<div class="row p-3 border">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="col-8 pt-4">
<div class="form-group row">
<div class="col-4">
<label asp-for="Product.Title"></label>
</div>
<div class="col-8">
<input asp-for="Product.Title" class="form-control" />
<span asp-validation-for="Product.Title" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-4">
Image
</div>
<div class="col-8">
<input type="file" name="files" id="uploadBox" multiple class="form-control"
/>
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-4">
@if (Model.Product.Id != 0)
{
<partial name="_EditAndBackToListButton" model="Model.Product.Id" />
}
else
{
<div class="row">
<div class="col">
<button type="submit" class="btn btn-primary form-control">Create</button>
</div>
<div class="col">
<button asp-action="Index" class="btn btn-success form-control">Back To List</button>
</div>
</div>
}
</div>
</div>
</div>
</div>
</form>
</div>
有没有nuget包可以压缩图片大小
【问题讨论】:
-
This nuget 调整大小、裁剪、添加文本水印、图像水印,甚至在动画 gif 上。
标签: asp.net asp.net-mvc asp.net-core asp.net-web-api asp.net-core-mvc