How to create thumbnail, small and large version of the uploaded image in Asp.net?

Introduction: In previous article i explained How to resize image in Asp.net and How to Validate and upload image files in asp.net  and jQuery to validate file extension and upload image file and Bind,upload,download,delete image files from the GridView  and Drag & drop to upload multiple files using AjaxFileUpload like Facebook and Upload and create Zip file and Maintain image on PostBack in FileUpload control
In this article i will explain with example How to create thumbnail image, small image  and large image version of the image uploaded through fileupload control  in Asp.net. 

Description: While working on asp.net application it is sometimes required to create thumbnail, small and large version of the image as per application requirement. Suppose there is image upload functionality in your website where user can upload their pictures and you want to store and display thumbnail, small and large version of the uploaded image. Here is the solution.

Implementation: Let's create an asp.net website to see the example in action.

Source Code:
  • In the design page (.aspx) place a FileUpload Control and a Button control as:
<table>
        <tr>
                <td>
                    <asp:FileUpload ID="FileUpload1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                      <asp:Button ID="btnUpload" runat="server" Text="Submit"
            onclick="btnUpload_Click" /></td>
          </tr>          
  </table>
  • Create a folder “images” and three sub folder “thumbnail”, “small” and “large” inside the folder “images”.
C#.NET Code to create thumbnail, small and large version of the uploaded image
  • In the code behind file (.aspx.cs) write the code as:
First Include following namespaces:

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Design;
using System.IO;
  • Then write the code as:
protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string imgThumb = string.Empty;
            string imgSmall = string.Empty;
            string imgLarge = string.Empty;
            Bitmap bmpImgThumb = null;
            Bitmap bmpImgSmall = null;
            Bitmap bmptImgLarge = null;
            try
            {
                bmpImgThumb = Resize_Image(FileUpload1.PostedFile.InputStream, 100, 67);
                bmpImgSmall = Resize_Image(FileUpload1.PostedFile.InputStream, 411, 274);
                bmptImgLarge = Resize_Image(FileUpload1.PostedFile.InputStream, 1280, 854);

                imgThumb = Server.MapPath("images/thumbnail/") + Guid.NewGuid().ToString() + ".png";
                imgSmall = Server.MapPath("images/small/") + Guid.NewGuid().ToString() + ".png";
                imgLarge = Server.MapPath("images/large/") + Guid.NewGuid().ToString() + ".png";

                bmpImgThumb.Save(imgThumb, ImageFormat.Jpeg);
                bmpImgSmall.Save(imgSmall, ImageFormat.Jpeg);
                bmptImgLarge.Save(imgLarge, ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                Response.Write("Error occured: " + ex.Message.ToString());              
            }
            finally
            {
                imgThumb = string.Empty;
                imgSmall = string.Empty;
                imgLarge = string.Empty;
                bmpImgThumb.Dispose();
                bmpImgSmall.Dispose();
                bmptImgLarge.Dispose();
            }
        }
    }
    private Bitmap Resize_Image(Stream streamImage, int maxWidth, int maxHeight)
    {
        Bitmap originalImage = new Bitmap(streamImage);
        int newWidth = originalImage.Width;
        int newHeight = originalImage.Height;
        double aspectRatio = Convert.ToDouble(originalImage.Width) / Convert.ToDouble(originalImage.Height);

        if (aspectRatio <= 1 && originalImage.Width > maxWidth)
        {
            newWidth = maxWidth;
            newHeight = Convert.ToInt32(Math.Round(newWidth / aspectRatio));
        }
        else if (aspectRatio > 1 && originalImage.Height > maxHeight)
        {
            newHeight = maxHeight;
            newWidth = Convert.ToInt32(Math.Round(newHeight * aspectRatio));
        }
        return new Bitmap(originalImage, newWidth, newHeight);
    }

VB.NET Code to create thumbnail, small and large version of the uploaded image
  • In the code behind file (.aspx.vb) write the code as:
First Include following namespaces:

Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Drawing.Imaging
Imports System.Drawing.Design
Imports System.IO
  • Then write the code as:
Protected Sub btnUpload_Click(ByVal sender As ObjectByVal e As System.EventArgsHandles btnUpload.Click

        If FileUpload1.HasFile Then
            Dim imgThumb As String = String.Empty
            Dim imgSmall As String = String.Empty
            Dim imgLarge As String = String.Empty
            Dim bmpImgThumb As Bitmap = Nothing
            Dim bmpImgSmall As Bitmap = Nothing
            Dim bmptImgLarge As Bitmap = Nothing
            Try
                bmpImgThumb = Resize_Image(FileUpload1.PostedFile.InputStream, 100, 67)
                bmpImgSmall = Resize_Image(FileUpload1.PostedFile.InputStream, 411, 274)
                bmptImgLarge = Resize_Image(FileUpload1.PostedFile.InputStream, 1280, 854)

                imgThumb = Server.MapPath("Images/thumbnail/") + Guid.NewGuid().ToString() + ".png"
                imgSmall = Server.MapPath("Images/small/") + Guid.NewGuid().ToString() + ".png"
                imgLarge = Server.MapPath("Images/large/") + Guid.NewGuid().ToString() + ".png"

                bmpImgThumb.Save(imgThumb, ImageFormat.Jpeg)
                bmpImgSmall.Save(imgSmall, ImageFormat.Jpeg)
                bmptImgLarge.Save(imgLarge, ImageFormat.Jpeg)
            Catch ex As Exception
                Response.Write("Error occured: " & ex.Message.ToString())
            Finally
                imgThumb = String.Empty
                imgSmall = String.Empty
                imgLarge = String.Empty
                bmpImgThumb.Dispose()
                bmpImgSmall.Dispose()
                bmptImgLarge.Dispose()
            End Try
        End If
    End Sub

    Private Function Resize_Image(ByVal streamImage As StreamByVal maxWidth As IntegerByVal maxHeight As IntegerAs Bitmap
        Dim originalImage As New Bitmap(streamImage)
        Dim newWidth As Integer = originalImage.Width
        Dim newHeight As Integer = originalImage.Height
        Dim aspectRatio As Double = Convert.ToDouble(originalImage.Width) / Convert.ToDouble(originalImage.Height)

        If aspectRatio <= 1 AndAlso originalImage.Width > maxWidth Then
            newWidth = maxWidth
            newHeight = Convert.ToInt32(Math.Round(newWidth / aspectRatio))
        ElseIf aspectRatio > 1 AndAlso originalImage.Height > maxHeight Then
            newHeight = maxHeight
            newWidth = Convert.ToInt32(Math.Round(newHeight * aspectRatio))
        End If
        Return New Bitmap(originalImage, newWidth, newHeight)
    End Function

Note: Uploaded image will be stored in three sub folders “thumbnail”, “small” and “large” inside the “images” folder of the root directory in our case. You can change the folder name, sub folder name and location as per your requirement.  Now you can display the thumbnail, small and large version of the image as per your requirement. 

Now over to you:

"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates."
Previous
Next Post »

1 comments:

Click here for comments
Unknown
admin
September 22, 2013 ×

Thanks,You helped me very much. can i ask you a favor if i want to create page to display images like windows explorer tree node in left hand and list on right and display images in list with check boxes has you and example or can you show me how to do that i appreciate that very much

Congrats bro Unknown you got PERTAMAX...! hehehehe...
Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..