Compress And Resize Image Using Web API

In this article we will learn how we can compress and resize image in Web API using postman and how we can save the compressed image. Here are the steps:

Step 1

In the first step, create a simple web API project. Go to File, then New and Project. Choose ASP.NET MVC 4 Web Application from the list, then provide the application name as you wish and click the OK button, then select Web API. Set the path to the location input where you want to create the application.

Let's see the Solution Explorer:



In our solution explorer we have an Uploadcontroller and ImgFloder.

Uploadcontroller contains the Post method. let's see the code for compressing and re-sizing the image.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Drawing2D;  
  5. using System.Drawing.Imaging;  
  6. using System.IO;  
  7. using System.Linq;  
  8. using System.Net;  
  9. using System.Net.Http;  
  10. using System.Net.Http.Headers;  
  11. using System.Web;  
  12. using System.Web.Http;  
  13.   
  14. namespace image_uplode.Controllers  
  15. {  
  16.     public class UplodeController : ApiController  
  17.     {  
  18.   
  19.         [HttpPost]  
  20.         public HttpResponseMessage Post()  
  21.         {  
  22.             HttpResponseMessage response = new HttpResponseMessage();  
  23.             var httpRequest = HttpContext.Current.Request;  
  24.             if (httpRequest.Files.Count > 0)  
  25.             {  
  26.                 var docfiles = new List<string>();  
  27.                 foreach (string file in httpRequest.Files)  
  28.                 {  
  29.                     var postedFile = httpRequest.Files[file];  
  30.                     var filePath1 = HttpContext.Current.Server.MapPath("~/ImgFolder/" + postedFile.FileName);  
  31.   
  32.                     Stream strm = postedFile.InputStream;  
  33.                    
  34.                     Compressimage(strm, filePath1, postedFile.FileName);  
  35.   
  36.                 }  
  37.                 response = Request.CreateResponse(HttpStatusCode.Created, docfiles);  
  38.             }  
  39.             else  
  40.             {  
  41.                 response = Request.CreateResponse(HttpStatusCode.BadRequest);  
  42.             }  
  43.             return response;  
  44.         }  
  45.         
  46.   
  47.         public static void Compressimage(Stream sourcePath, string targetPath, String filename)  
  48.         {  
  49.   
  50.   
  51.             try  
  52.             {  
  53.                 using (var image = Image.FromStream(sourcePath))  
  54.                 {  
  55.                     float maxHeight = 900.0f;  
  56.                     float maxWidth = 900.0f;  
  57.                     int newWidth;  
  58.                     int newHeight;  
  59.                     string extension;  
  60.                     Bitmap originalBMP = new Bitmap(sourcePath);  
  61.                     int originalWidth = originalBMP.Width;  
  62.                     int originalHeight = originalBMP.Height;  
  63.   
  64.                     if (originalWidth > maxWidth || originalHeight > maxHeight)  
  65.                     {  
  66.   
  67.                         // To preserve the aspect ratio  
  68.                         float ratioX = (float)maxWidth / (float)originalWidth;  
  69.                         float ratioY = (float)maxHeight / (float)originalHeight;  
  70.                         float ratio = Math.Min(ratioX, ratioY);  
  71.                         newWidth = (int)(originalWidth * ratio);  
  72.                         newHeight = (int)(originalHeight * ratio);  
  73.                     }  
  74.                     else  
  75.                     {  
  76.                         newWidth = (int)originalWidth;  
  77.                         newHeight = (int)originalHeight;  
  78.   
  79.                     }  
  80.                     Bitmap bitMAP1 = new Bitmap(originalBMP, newWidth, newHeight);  
  81.                     Graphics imgGraph = Graphics.FromImage(bitMAP1);  
  82.                     extension = Path.GetExtension(targetPath);  
  83.                     if (extension == ".png" || extension == ".gif")  
  84.                     {  
  85.                         imgGraph.SmoothingMode = SmoothingMode.AntiAlias;  
  86.                         imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  87.                         imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight);  

  88.   
  89.                         bitMAP1.Save(targetPath, image.RawFormat);  
  90.   
  91.                         bitMAP1.Dispose();  
  92.                         imgGraph.Dispose();  
  93.                         originalBMP.Dispose();  
  94.                     }  
  95.                     else if (extension == ".jpg")  
  96.                     {  
  97.   
  98.                         imgGraph.SmoothingMode = SmoothingMode.AntiAlias;  
  99.                         imgGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;  
  100.                         imgGraph.DrawImage(originalBMP, 0, 0, newWidth, newHeight);  
  101.                         ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);  
  102.                         Encoder myEncoder = Encoder.Quality;  
  103.                         EncoderParameters myEncoderParameters = new EncoderParameters(1);  
  104.                         EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);  
  105.                         myEncoderParameters.Param[0] = myEncoderParameter;  
  106.                         bitMAP1.Save(targetPath, jpgEncoder, myEncoderParameters);  
  107.   
  108.                         bitMAP1.Dispose();  
  109.                         imgGraph.Dispose();  
  110.                         originalBMP.Dispose();  
  111.   
  112.                     }  
  113.   
  114.                    
  115.                 }  
  116.   
  117.             }  
  118.             catch (Exception)  
  119.             {  
  120.                 throw;  
  121.   
  122.             }  
  123.         }  
  124.   
  125.   
  126.         public static ImageCodecInfo GetEncoder(ImageFormat format)  
  127.         {  
  128.   
  129.             ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();  
  130.   
  131.             foreach (ImageCodecInfo codec in codecs)  
  132.             {  
  133.                 if (codec.FormatID == format.Guid)  
  134.                 {  
  135.                     return codec;  
  136.                 }  
  137.             }  
  138.             return null;  
  139.         }  
  140.   
  141.     }  
  142. }  
After that run your application.

Now call the post method, here I am using postman for post call, let's see what we need for post call. It is shown in the following screenshot:



In the above snapshot I clicked on the body select form-data and in key column of the form-data wrote file and choose file from dropdown list.
Also add one more row  size : original, after that choose the file from directory.

After that click Headers and add one row Accept: multipart/form-data.



Summary

In this article we learned about compressing images and re-sizing them in web API using postman.


Similar Articles