Create Thumbnail of an Image using MVC

In this article I am going to show you how to create a thumbnail during image upload using MVC. If we create a thumbnail of images then it reduces the image byte size with its dimension. If we create a thumbnail of 700 KB file then thumbnail’s file size would be less than 25 KB. .NET provides Image class and its one method can create a thumbnail but reducing the dimension of image with its ratio is very important.

First of all we will create a Model to store the image path into database. This approach is totally optional, if you don’t want to store the image path into database.

  1. Public class ImageUploadModels   
  2. {  
  3.     [Key]  
  4.     Public int ImgageID   
  5.     {  
  6.         get;  
  7.         set;  
  8.     }  
  9.     [Required]  
  10.     Public string ImagePath   
  11.     {  
  12.         get;  
  13.         set;  
  14.     }  
  15. }  

 

Now we add “ImageUploadThumnail” action into "HomeController" controller. Below is the snap-shot of “ImageUploadThumnail” action method. In this method we are getting "ImageUploadModels" and "HttpPostedFileBase".

  1. [HttpPost]  
  2. Public ActionResult ImageUploadThumnail(ImageUploadModels image, HttpPostedFileBase file)   
  3. {  
  4.     try {  
  5.         if (file != null)  
  6.         {  
  7.             varfileName = Path.GetFileName(file.FileName);  
  8.             varthumbName = fileName.Split('.').ElementAt(0) + "_thumb." + fileName.Split('.').ElementAt(1);  
  9.             fileName = Path.Combine(Server.MapPath("/Images"), fileName);  
  10.             thumbName = Path.Combine(Server.MapPath("/Images"), thumbName);  
  11.             image.ImagePath = fileName; //to store into database, if we use DbContext  
  12.             file.SaveAs(fileName);  
  13.             Imageimg = Image.FromFile(fileName);  
  14.             intimgHeight = 100;  
  15.             intimgWidth = 100;  
  16.             if (img.Width < img.Height)  
  17.             {  
  18.                 //portrait image  
  19.                 imgHeight = 100;  
  20.                 varimgRatio = (float) imgHeight / (float) img.Height;  
  21.                 imgWidth = Convert.ToInt32(img.Height * imgRatio);  
  22.             }  
  23.             elseif(img.Height < img.Width)  
  24.             {  
  25.                 //landscape image  
  26.                 imgWidth = 100;  
  27.                 varimgRatio = (float) imgWidth / (float) img.Width;  
  28.                 imgHeight = Convert.ToInt32(img.Height * imgRatio);  
  29.             }  
  30.             Image thumb = img.GetThumbnailImage(imgWidth, imgHeight, () => false, IntPtr.Zero);  
  31.             thumb.Save(thumbName);  
  32.         }  
  33.         return View();  
  34.     } catch (Exception ex)  
  35.     {  
  36.         ViewBag.Message = ex.Message.ToString();  
  37.         return View();  
  38.     }  
  39. }  
In the above method we are checking whether the image is portrait or landscape. Maximum width or height should be 100 pixels so we are getting ratio of actual height and width for 100 pixel size image. "GetThumbnailImage()" function is used to create a thumbnail of an image. It accepts new width, height, GetThumbnailImageAbort delegate and System.IntPtr.Zero parameters. This function returns Image type object. "Save()" function is used to save the thumbnail file into any specific folder. To save the thumbnail we are using actual file name with “_thumb” suffix and it will save the thumbnail into the same folder where we are saving actual image.

Now we create a view named “ImageUploadThumnail.cshtml” in Home folder of Views. Below is the snap-shot of view.
  1. @model KnowckoutMvcApp.Models.ImageUploadModels  
  2. @using(Html.BeginForm("ImageUploadThumnail""Home"null, FormMethod.Post, new {  
  3.     enctype = "multipart/form-data"  
  4. })) {  
  5.     @Html.AntiForgeryToken()  
  6.     @Html.ValidationSummary(true); < fieldset > < legend > Image < /legend> < divclass = "editor-label" > @Html.LabelFor(model => model.ImagePath) < /div> < divclass = "editor-field" > < inputid = "ImagePath"  
  7.     title = "Upload an image"  
  8.     type = "file"  
  9.     name = "file" / > < /div> < p > < inputtype = "submit"  
  10.     value = "Upload" / > < /p> < /fieldset>  
  11. }  
In the above view, we are using Html.BeginForm helper and it is pointing Create action method of ImageUpload controller. For HttpPostedFileBase we use enctype = “multipart/form-data” as additional html attribute. Now if we run the code then you will get the bellow output:

output

If we upload any large image then it will store the image in Image folder of solution and will create a new file with “_thumb” suffix, which will be a thumbnail of actual image. Below is the image of Image folder.

 

folder

folder
Ebook Download
View all
Learn
View all