Compress image using ImageCompress NuGet package
ImageCompress
This nuget package is a free third party package which you can install in your project and then add code for compressing image in few steps. So we will see how to use this.
Step 1: Install the NuGet package in the solution
Install-Package ImageCompress -Version 1.0.0
So, first of all you have to install this nuget package which you can do by using the command which is mentioned above or you can install the package which is shown in below image.
After, you have done installing the package you can now use the package, you can create one action as you can see in below image and that is where we will get our file which we have to compress . As our package requires the file in byte array , we have to convert the file to byte array to compress it.
[HttpPost] public ActionResult Compression(HttpPostedFileBase file) { try { using (var mS = new MemoryStream()) { var targetpath = Server.MapPath("/Content/Compressed/"); var imageName = Path.GetFileNameWithoutExtension(file.FileName) + "_Compressed" + DateTime.Now.ToString("ddMMyyyyhhmmss") + Path.GetExtension(file.FileName); byte[] image = new byte[file.ContentLength]; file.InputStream.Read(image, 0, image.Length); CompressImage.CompressingImage(targetpath, imageName, image, 900.0f, 900.0f); } } catch (Exception ex) { string exc = ex.Message; } return RedirectToAction("Index"); }
Now on the view we will add a form , where we will add one fileupload control and there we will select the image file which we will compress before saving on our controller.
@{ ViewBag.Title = "Home Page"; } @using (Html.BeginForm("Compression", "Home", FormMethod.Post, new {@enctype="multipart/form-data" })) { <input type="file" id="file" name="file"/> <input type="submit" value="Save"/> }
Now, run your application and you will get option to select image. Now select any image file which is large in size and than click on save.You will notice the file saved in compressed folder is so much less in size than what we have upload. So, this is how we can Compress image using ImageCompress NuGet package in Asp.Net.