×

iFour Logo

Generate Thumbnail Using ASP.NET MVC

Kapil Panchal - July 06, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Generate Thumbnail Using ASP.NET MVC

What is a Thumbnail?


Thumbnail is an image with a reduced file size of the actual image that is used as at a time of uploading image.

Why We Use Thumbnails?


The main advantage of thumbnail image is to reduce the file size using thumbnail image to load websites faster compared to the original image. If the user wants to show the original image by clicking the thumbnail images.

Using thumbnails, the website provides the user or visitor lots of instantaneous content without requiring extra time for loading.

With the help of thumbnail images, we display larger content in a small space.

When Thumbnails Are Useful?


Thumbnail images can be used in online everywhere. For example - YouTube uses thumbnail and google image search, Pinterest use the thumbnail. All the Online Shopping websites use the thumbnail image to display more products and faster loading of products. When you click on the thumbnail image shows the original image.

Some Examples for Thumbnails


Our computer system uses the thumbnails image like we open the image folder you can see that image size is reducing and display more image compared to original images and it takes less time to load all the images inside your image folder.

Amazon uses thumbnails image to display their product. It displays thumbnails image in the list of all product when user click on the thumbnail image, it displays the original image.

Generate Thumbnails Image


In this example, I will show you how to create thumbnail while uploading an image to a database using MVC. image thumbnail we reduce the image file size and then the original image.

I will use the code-first approach to implements image thumbnails. In the code first approach, we have to create a modal for image upload.

you can add model to our solution Models -> Add -> Ado.Net Entity Data model

 Ado.Net Entity Data Model

Fig :- Ado.Net Entity Data Model

Model code:
public class ImageUpload
{
     [Key]
         public int  Image_Id
        {
            get;
            set;
          }
         [Required]
         public string Image_Path
         {
            get;
            set;
         }
 }
				
 

 Empty Code First model

Fig :- Empty Code First model

This will create a context file for your database connection. You can now add your model within the context file shown below.

public class thumbnails: DbContext
{ 
    public thumbnails() : base("name=thumbnails")
    {
    }
    public virtual DbSet ImageUploads { get; set; }
}

				

Now you need to execute the Migration command within the package manager control

Create New Controller and then create the ThumbnailImage method inside the new controller.

 
public ActionResult ThumbnailImage(ImageUpload imageUpload, HttpPostedFileBase file)
        {
            thumbnails db = new thumbnails();
            try
            {
                if (file != null)
                {
                    ImageUpload image = new ImageUpload();
                    var fileName = Path.GetFileName(file.FileName);
                    var thumbName = fileName.Split('.').ElementAt(0) + "_thumb." + fileName.Split('.').ElementAt(1);
                    fileName = Path.Combine(Server.MapPath("/Images"), fileName);
                    thumbName = Path.Combine(Server.MapPath("/Images"), thumbName);
                    image.Iamge_Path = fileName;
                    db.ImageUploads.Add(image);
                    file.SaveAs(fileName);
                    Image img = Image.FromFile(fileName);
                    int imgHeight = 150;
                    int imgWidth = 150;
                    if (img.Width < img.Height)
                    {
                        //portrait image  
                        imgHeight = 150;
                        var imgRatio = (float)imgHeight / (float)img.Height;
                        imgWidth = Convert.ToInt32(img.Height * imgRatio);
                    }
                    else if (img.Height < img.Width)
                    {
                        //landscape image  
                        imgWidth = 150;
                        var imgRatio = (float)imgWidth / (float)img.Width;
                        imgHeight = Convert.ToInt32(img.Height * imgRatio);
                    }
                    Image thumb = img.GetThumbnailImage(imgWidth, imgHeight, () => false, IntPtr.Zero);
                    thumb.Save(thumbName);
                }
                return View();
            }
            catch (Exception ex)
            {
                ViewBag.Message = ex.Message.ToString();
                return View();
            }
        }
				

In this method, I passed the two parameters, one is our model name ImageUpload and the second parameter is HttpPostedFileBase.

HttpPostedFileBase is an abstract class that its member is the similar to HttpPostedFile.HttpPostedFileBase allows you to customize it according to your needs.

We need to provide the object of a database connection. To connect our data table, we need to create its own object.

Through our ThumbnailImage () method we view a portrait or landscape image. The maximum height or width is 150 pixels so we get an image length and width of 150 pixels within the shape.

Asp.Net provides the GetThumbnailImage () method for creating the thumbnail image. Accept new width, height, GetThumbnailImageAbort messenger, and System.IntPtr.Zero parameter. This function returns the image of the object type.

The "Save ()" function is used to save the icon file to any specific folder. Saving the icon uses a real file name with the suffix "_thumb" and will keep the icon in the same folder where we saved the image so I use the suffix for thumbnail image so we can easily identify the thumbnails image. If you are using two separate folders to store the actual and thumbnail image in that case it does not require the suffix.

Looking for Trusted Dot Net Development Company ? Your Search ends here.

If you want to store the thumbnails image in a different folder you can change this code. Here I change the Image folder to ThumbImg.


thumbName = Path.Combine(Server.MapPath("/ThumbImg"), fileName);
				

Here is my view code and I created the image capturing form in the database.

Inside the Html.BeginForm() we need tho pass our method name and controller name with the post method and provide the new { enctype = "multipart/form-data" } .That is required when we use the post method so we can send our data in the form of encoding.


@model ImageThumbnails.Models.ImageUpload
@{
    ViewBag.Title = "ThumbnailImage";
}

ThumbnailImage

@using (Html.BeginForm("ThumbnailImage", "thumbnail", null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken()

ImageUpload


@Html.LabelFor(model => model.Image_Path, htmlAttributes: new { @class = "control-label col-md-2" })
}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Now Run the code and you will get the below output. When we upload the original image we will insert the original image into our project solution within the Image folder and save the thumbnail image in the same folder because we use the same folder to store both the image. You need to create an Image folder inside your project solution to store the images.

 Image upload view

Fig :- Image upload view

Conclusion


With the help of the thumbnail image approach, we can display more images in limited space. Thumbnails image save space and it take less time for loading the image. If we use the original image to display on a website, it takes more time to load the website because its size is very large than the thumbnail image.

Generate Thumbnail Using ASP.NET MVC Table of Content 1. What is a Thumbnail? 2. Why We Use Thumbnails? 3. When Thumbnails Are Useful? 4. Some Examples for Thumbnails 5. Generate Thumbnails Image 6. Conclusion What is a Thumbnail? Thumbnail is an image with a reduced file size of the actual image that is used as at a time of uploading image. Why We Use Thumbnails? The main advantage of thumbnail image is to reduce the file size using thumbnail image to load websites faster compared to the original image. If the user wants to show the original image by clicking the thumbnail images. Using thumbnails, the website provides the user or visitor lots of instantaneous content without requiring extra time for loading. With the help of thumbnail images, we display larger content in a small space. When Thumbnails Are Useful? Thumbnail images can be used in online everywhere. For example - YouTube uses thumbnail and google image search, Pinterest use the thumbnail. All the Online Shopping websites use the thumbnail image to display more products and faster loading of products. When you click on the thumbnail image shows the original image. Some Examples for Thumbnails Our computer system uses the thumbnails image like we open the image folder you can see that image size is reducing and display more image compared to original images and it takes less time to load all the images inside your image folder. Amazon uses thumbnails image to display their product. It displays thumbnails image in the list of all product when user click on the thumbnail image, it displays the original image. Generate Thumbnails Image In this example, I will show you how to create thumbnail while uploading an image to a database using MVC. image thumbnail we reduce the image file size and then the original image. I will use the code-first approach to implements image thumbnails. In the code first approach, we have to create a modal for image upload. you can add model to our solution Models -> Add -> Ado.Net Entity Data model Fig :- Ado.Net Entity Data Model Model code: public class ImageUpload { [Key] public int Image_Id { get; set; } [Required] public string Image_Path { get; set; } } Read More: What Is Form Collection And How To Implement It In Asp .net Mvc?   Fig :- Empty Code First model This will create a context file for your database connection. You can now add your model within the context file shown below. public class thumbnails: DbContext { public thumbnails() : base("name=thumbnails") { } public virtual DbSet ImageUploads { get; set; } } Now you need to execute the Migration command within the package manager control Create New Controller and then create the ThumbnailImage method inside the new controller.   public ActionResult ThumbnailImage(ImageUpload imageUpload, HttpPostedFileBase file) { thumbnails db = new thumbnails(); try { if (file != null) { ImageUpload image = new ImageUpload(); var fileName = Path.GetFileName(file.FileName); var thumbName = fileName.Split('.').ElementAt(0) + "_thumb." + fileName.Split('.').ElementAt(1); fileName = Path.Combine(Server.MapPath("/Images"), fileName); thumbName = Path.Combine(Server.MapPath("/Images"), thumbName); image.Iamge_Path = fileName; db.ImageUploads.Add(image); file.SaveAs(fileName); Image img = Image.FromFile(fileName); int imgHeight = 150; int imgWidth = 150; if (img.Width < img.Height) { //portrait image imgHeight = 150; var imgRatio = (float)imgHeight / (float)img.Height; imgWidth = Convert.ToInt32(img.Height * imgRatio); } else if (img.Height < img.Width) { //landscape image imgWidth = 150; var imgRatio = (float)imgWidth / (float)img.Width; imgHeight = Convert.ToInt32(img.Height * imgRatio); } Image thumb = img.GetThumbnailImage(imgWidth, imgHeight, () => false, IntPtr.Zero); thumb.Save(thumbName); } return View(); } catch (Exception ex) { ViewBag.Message = ex.Message.ToString(); return View(); } } In this method, I passed the two parameters, one is our model name ImageUpload and the second parameter is HttpPostedFileBase. HttpPostedFileBase is an abstract class that its member is the similar to HttpPostedFile.HttpPostedFileBase allows you to customize it according to your needs. We need to provide the object of a database connection. To connect our data table, we need to create its own object. Through our ThumbnailImage () method we view a portrait or landscape image. The maximum height or width is 150 pixels so we get an image length and width of 150 pixels within the shape. Asp.Net provides the GetThumbnailImage () method for creating the thumbnail image. Accept new width, height, GetThumbnailImageAbort messenger, and System.IntPtr.Zero parameter. This function returns the image of the object type. The "Save ()" function is used to save the icon file to any specific folder. Saving the icon uses a real file name with the suffix "_thumb" and will keep the icon in the same folder where we saved the image so I use the suffix for thumbnail image so we can easily identify the thumbnails image. If you are using two separate folders to store the actual and thumbnail image in that case it does not require the suffix. Looking for Trusted Dot Net Development Company ? Your Search ends here. See here If you want to store the thumbnails image in a different folder you can change this code. Here I change the Image folder to ThumbImg. thumbName = Path.Combine(Server.MapPath("/ThumbImg"), fileName); Here is my view code and I created the image capturing form in the database. Inside the Html.BeginForm() we need tho pass our method name and controller name with the post method and provide the new { enctype = "multipart/form-data" } .That is required when we use the post method so we can send our data in the form of encoding. @model ImageThumbnails.Models.ImageUpload @{ ViewBag.Title = "ThumbnailImage"; }ThumbnailImage @using (Html.BeginForm("ThumbnailImage", "thumbnail", null, FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() ImageUpload @Html.LabelFor(model => model.Image_Path, htmlAttributes: new { @class = "control-label col-md-2" }) } @Html.ActionLink("Back to List", "Index") @section Scripts { @Scripts.Render("~/bundles/jqueryval") } Now Run the code and you will get the below output. When we upload the original image we will insert the original image into our project solution within the Image folder and save the thumbnail image in the same folder because we use the same folder to store both the image. You need to create an Image folder inside your project solution to store the images. Fig :- Image upload view Conclusion With the help of the thumbnail image approach, we can display more images in limited space. Thumbnails image save space and it take less time for loading the image. If we use the original image to display on a website, it takes more time to load the website because its size is very large than the thumbnail image.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
Location Intelligence Use Cases, and Benefits
Location Intelligence Use Cases, and Benefits

You must be wondering what exactly is Location Intelligence. To put it simply, it is basically a way of deriving actionable insights from geographic data and spatial relationships...

13 Ways Power Apps Simplifies eDiscovery
13 Ways Power Apps Simplifies eDiscovery

E-Discovery is a crucial process for legal research enabling lawyers to find the digital evidence they need. It involves finding, collecting, and filtering e-data related to their...

Top Data Analytics Trends You Can't Ignore
Top Data Analytics Trends You Can't Ignore

Can you believe that 147 zettabytes of data have already been created in 2024, and guess what? It is anticipated to be 180 zettabytes by 2025 (according to Statista). Now just think...