How To Create Image Thumbnail In ASP.NET Applications

In this article, we will learn how to create thumbnails of images while uploading the images in ASP.NET MVC. The concept is the same for ASP.NET too. It is very important to create thumbnails of images of different sizes, depending upon the scenario and type of application. If we create a thumbnail of an image, it reduces the image byte size along with its dimension, resulting in a fast processing of page.

If we create a thumbnail of a 1500 KB image file, the thumbnail’s size would be less than 50 KB. .NET provides image class and its one method can create a thumbnail too, but reducing the dimension of the image with its ratio is very important.

The main advantage of using thumbnails is the improvement in application performance beacuse they load faster and process quickly. So, let's start. 

Create an MVC Project

Step 1 : Open Visual Studio.

Step 2 : Go to File => New Project.

  1. Select Visual C# => Web => ASP.NET Web Application.
  2. Name your solution (eg. EasyCRM) and Project (EasyCRM.UI); then, click OK.
  3. Select MVC.
  4. Change authentication to "Individual Accounts".


Now, you will see the following screen.



Creating Image Handler

Step 1: Create a new folder called ImageHandler.

Step 2: Add a new class called UploadImage.

Step 3: Add a function called "Crop" with parameters described below.

 S.No Type Description
 Width int New width of Image
 Height int New Height of Image
 streamIMg Stream Image Stream
 SaveFilePath string Path of server where file is saved. (Eg. "~/Upload/Images/thumb")

Step 4

Add the following lines of code to the "Crop" method.
  1. public class UploadImage 
  2.    {  
  3.     public static void Crop(int Width, int Height, Stream streamImg, string saveFilePath) 
  4.       {  
  5.         Bitmap sourceImage = new Bitmap(streamImg);  
  6.         using(Bitmap objBitmap = new Bitmap(Width, Height))
  7.         {  
  8.             objBitmap.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution);  
  9.             using(Graphics objGraphics = Graphics.FromImage(objBitmap))
  10.             {  
  11.                 // Set the graphic format for better result cropping   
  12.                 objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;  

  13.                 objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;  
  14.                 objGraphics.DrawImage(sourceImage, 0, 0, Width, Height);  

  15.                 // Save the file path, note we use png format to support png file   
  16.                 objBitmap.Save(saveFilePath);  
  17.             }  
  18.         }  
  19.     }  
  20. }  
UploadImage classs looks like this in Solution Explorer.

So far, we have created a method to resize and save the image.

Now, let's build a Controller which will help to,

  • display a form to upload images.
  • upload selected images to the "Upload" folder.
Adding Controller

Step 1

Add a Controller called Manage_Gallery.

Step 2

Add a method called AddPhotoGallery().
  1. public ActionResult AddPhotoGallery() {  
  2.     return View();  
  3. }  

Step 3 

Add a View for this method (For now, I am creating an empty View).

Step 4

Let's add the following lines of code in View.
  1. @ {  
  2.     ViewBag.Title = "Add Photo Gallery";  
  3.     Layout = "~/Views/Shared/_LayoutAdminPanel.cshtml";  

  4. <h2> Add Photo Gallery </h2>
  5.   
  6. @ * @using(Html.BeginForm("Method_Name""Controller_Name", FormMethod(Post / GET), new {  
  7.     enctype = "multipart/form-data", area = "Area_Name"  
  8. })) * @  

  9. @using(Html.BeginForm("AddPhotoGallery""Manage_Gallery", FormMethod.Post, new {  
  10.     enctype = "multipart/form-data", area = "SuperAdmin"  
  11. })) 

  12. {  
  13.     @Html.AntiForgeryToken() < div class = "form-orizontal" > <h4 > Create New Image Gallery </h4> 
  14. <hr /> 

  15.    @Html.ValidationSummary(true""new {@class = "text-danger"}) 

  16.   <div class="form-group"
  17.      <div class="col-md-2"> Select Images </div>
  18.      <div class="col-md-10">
  19.         <input type ="file" name="Images" value="Select Images" id="Images" multiple /> 
  20.      </div> 
  21.   </div> 

  22.   <div class = "form-group">
  23.       <div class = "col-md-offset-2 col-md-10" >
  24.          <input type = "submit" value = "Save" class = "btn btn-success" /> 
  25.       </div> 
  26.   </div>

  27. </div>

  28.   
  29. }  
  30. @section Scripts {  
  31.     @Scripts.Render("~/bundles/jqueryval")  
  32. }  

Step 5

Now, add a method called AddPhotoGallery on the same Controller (Don't forget to mention the method as Post type, by adding [HttpPost]).
 
Add the following lines of code. Your method should look like below.
  1. /// <summary>  
  2. /// method to create thumbnail of the images uploaded  
  3. /// </summary>  
  4. /// <param name="Images">Uploaded Images (can be multiple or single)</param>  
  5. /// <returns></returns>  
  6. [HttpPost]  
  7. public ActionResult AddPhotoGallery(IEnumerable <HttpPostedFileBase> Images)
  8.  {  
  9.     try 
  10.       {  
  11.         foreach(var image in Images) {  
  12.             if (image != null)
  13.             {  
  14.                 string fileName = Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);  
  15.                 var path = Path.Combine(Server.MapPath("~/Upload/Images/"), fileName);  
  16.                 image.SaveAs(path);  
  17.                 UploadImage.Crop(320, 240, image.InputStream, Path.Combine(Server.MapPath("~/Upload/Images/thumb/") + fileName));  
  18.             }  
  19.         }  
  20.         TempData["MessageValue"] = "1";  
  21.         TempData["Message"] = "Image Gallery added successfully";  
  22.     } 

  23.     catch 
  24.         {  
  25.         TempData["MessageValue"] = "0";  
  26.         TempData["Message"] = "Error occured while adding Image Galley";  
  27.         }  
  28.     return RedirectToAction("Index""Manage_Gallery"new {area = "SuperAdmin"  });  
  29. }  

Step 6 

Now, run the application. You will be able to see the following screen.

File Browser

Step 7
 
Now, select an image and upload it.



You will be able to see the uploaded images and thumbnail images  in "Images" and "thumb" folder respectively.


Note
 
Don't forget to add Upload Folder in Project. Also add Images folder inside Upload folder. Add thumb folder inside Images Folder as below.

Upload Folder

If you have any queries, please feel free to comment.

I hope now you will be able to write your own codes for creating thumbnails of images and upload images in C#.

You may also like


Similar Articles