DEV Community

Cover image for Generate Thumbnail Using ASP.NET MVC - iFour Technolab
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

Generate Thumbnail Using ASP.NET MVC - iFour Technolab

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

Image description

Model code:


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

Enter fullscreen mode Exit fullscreen mode

Read More: What Is Form Collection And How To Implement It In Asp .NET Mvc?

Image description

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<imageupload> ImageUploads { get; set; }
}
</imageupload>

Enter fullscreen mode Exit fullscreen mode

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();
            }
        }

Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode

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.


<xmp>
@model ImageThumbnails.Models.ImageUpload
@{
    ViewBag.Title = &quot;ThumbnailImage&quot;;
}<h2>ThumbnailImage</h2>
@using (Html.BeginForm(&quot;ThumbnailImage&quot;, &quot;thumbnail&quot;, null, FormMethod.Post, new { enctype = &quot;multipart/form-data&quot; }))
{
    @Html.AntiForgeryToken()
<div class="form-horizontal"><h4>ImageUpload</h4>
<hr /><div class="form-group">
            @Html.LabelFor(model => model.Image_Path, htmlAttributes: new { @class = &quot;control-label col-md-2&quot; })<div class="col-md-10">
                <input class="form-control" name="image" required="" type="file" /></div></div>
<div class="form-group"><div class="col-md-offset-2 col-md-10">
                <input class="btn btn-info" type="submit" value="Upload" /></div></div></div>
}
<div>
    @Html.ActionLink(&quot;Back to List&quot;, &quot;Index&quot;)</div>
@section Scripts {
    @Scripts.Render(&quot;~/bundles/jqueryval&quot;)
}
</xmp>

Enter fullscreen mode Exit fullscreen mode

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 description

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.

Top comments (0)