-->

How to upload image and generate thumbnails dynamically from an original big image.

Introduction

In this tutorial, I explain how to upload an image and generate thumbnails dynamically from an original big image.

Many developers upload big images and show as small by giving the attribute values for the image tag. This will slow down the performance of web forms loading. For better performance the best method is creating the small thumbnail images for showing small size image on the web pages.

In this example, I have created a web page for upload image and show list of Thumbnail of uploaded image with a link for view full-size image.


Steps :

Step - 1 : Create New Project

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step - 2: Add 2 Folder for save Image & Image thumbnail.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New Folder > Enter Folder name.

Step - 3: Add a Webpage and Design for Save Image and Show Image.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.
Here in this example, I have added a File Uploader, a Button and a DataList Control(from show thumbnail image).

HTML CODE 
<h3>Upload image with Thumbnail</h3>
    <hr />
    <div>
        Select Image : 
        <asp:FileUpload ID="FileUpload1" runat="server" />
        &nbsp;
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
    </div>
    <div>
        <br />
        <br />
        <div>
        <asp:DataList ID="DataList1" runat="server" RepeatColumns="3"
            RepeatDirection="Horizontal" BackColor="White" BorderColor="#CC9966"
            BorderStyle="None" BorderWidth="1px" CellPadding="4" GridLines="Both">
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
            <ItemStyle BackColor="White" ForeColor="#330099" />
            <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
            <ItemTemplate>
                <div style="text-align:center">
                    <div><img src="/Thumbnail/<%#Eval("FileName")%>" /></div>
                    <div ><%#Eval("FileSize")%> KB</div>
                    <div><a target="_blank" href='/Images/<%#Eval("FileName")%>'>View Full Size</a> </div>
                </div>
            </ItemTemplate>
        </asp:DataList>
    </div>
    </div>

Step-4: Add a Class.

Here I have added a class for getting Image info into this class.

Class Code
public class MyImageFiles
{
    public string FileName { get; set; }
    public string FileSize { get; set; }
}

Step-5: Add required namespaces.

Add this namespace to the top of your page(Code behind).

using System;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Web.UI;

Step-6: Add Code For Save Image with Thumbnail.

Write the followings code in Button Click event for save image and thumbnail of the image.
Here I have created a folder Name "Thumbnail" for Save image thumbnail & Save Full size image in Images folder.

protected void btnUpload_Click(object sender, EventArgs e)
{
    string uploadedFileName = FileUpload1.PostedFile.FileName;
    Image img = Image.FromStream(FileUpload1.PostedFile.InputStream);
    string ext = Path.GetExtension(uploadedFileName);

    string uploadFilePath = DateTime.Now.ToString("ddMMyyyyhhmmsstt");
    string imageFile = uploadFilePath + ext;
    try
    {
        FileUpload1.PostedFile.SaveAs(Path.Combine(Server.MapPath("~/Images"), imageFile));
        var ratio = (double)100 / img.Height;
        int imageHeight = (int)(img.Height * ratio);
        int imageWidth = (int)(img.Width * ratio);

        Image.GetThumbnailImageAbort dCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);
        Image thumbnailImg = img.GetThumbnailImage(imageWidth, imageHeight, dCallback, IntPtr.Zero);

        thumbnailImg.Save(Path.Combine(Server.MapPath("~/Thumbnail"), imageFile), ImageFormat.Jpeg);
        thumbnailImg.Dispose();

        //Here Code for Get Uploaded Images
        PopulateImage();
    }
    catch (Exception ex)
    {
        throw;
    }
}

Step-7: Add Code For show uploaded images.

Write the followings code in Page_Load event for Show Uploaded image thumbnail.

if (!IsPostBack)
{
    PopulateImage();
}

And Here is the function code 
private void PopulateImage()
{
    DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Images"));
    List<MyImageFiles> images = new List<MyImageFiles>();
    foreach (var i in dir.GetFiles())
    {
        images.Add(new MyImageFiles { FileName = i.Name, FileSize = (i.Length/1024).ToString() });
    }
    DataList1.DataSource = images;
    DataList1.DataBind();
}

Step-8: Run Application.

Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.