Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compress an image from IFormFile before upload to the server ASP.Net Core

I have a problem, I'm creating an app in net core, to upload kids information, but, the main problem is than all the image I have are from my phone and you know than we are talking about 9-15 MB per picture, so, I know than I can tell the user "There's a limitation" but, I thinks than that its not useful, so, There's a way to reduce the size of the image loosing the less quality possible?.

This is my Method

Class

public IFormFile ImageFile { get; set; }

Method

if (vm.ImageFile != null && vm.ImageFile.Length > 0)
{
    var guid = Guid.NewGuid().ToString();
    var file = $"{guid}.jpg";

    path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\Kids", file);

    using (var stream = new FileStream(path, FileMode.Create))
    {
        //var convertedImage = MagicSolutionGivenByTheAwsomeStackOverFlowCommunity
        await vm.ImageFile.CopyToAsync(stream);
    }

}

Layout

<form asp-action="Create" enctype="multipart/form-data">
 <input type="hidden" asp-for="Imagen"/>
  <div class="col-sm-4">
   <label asp-for="Imagen" class="control-label"></label>
   <div>
    <input asp-for="ImageFile" class="form-control filestyle"
           type="file" data-classbutton="btn btn-secondary"
           data-classinput="form-control inline"
           data-icon="&lt;span class='fa fa-upload mr'&gt;&lt;/span&gt;" />
   </div>
  <span asp-validation-for="Imagen" class="text-danger"></span>
 </div>
</form>
like image 294
sgrysoft Avatar asked Feb 04 '20 14:02

sgrysoft


1 Answers

For my projects I usually use this library on backend: ImageResizer Here from Nuget: nuget ImageResizer

It's useful for compression and resizing server-side

Instead I use this in JS on frontend: PlUpload

In this example you can resize the image on the client Image-Resizing-on-Client-Side or you can use Chunking to speed up the upload to the client and manage the file on the server.

like image 171
tartarismo Avatar answered Sep 26 '22 20:09

tartarismo