Asp.Net News
Free Tech Magazines
Asp.Net Web Hosting
Suggest Us
Link to Us
Feeds Subscription
Questions & Answers
Tips & Tricks
 Dynamic Thumbnail Images Creation in Asp.Net
Posted by Moderator1 on 7/4/2008 9:55:22 AM Category: Asp.Net 2.0
Total Views : 73441
Add to my favorites
Email to friend
This article explains the two best ways to create thumbnail images dynamically in Asp.Net.
There are several situations in website development that deals with images and to display it in Thumbnail sizes. Its really hectic to display the thumbnail images without any distortion and to maintain the quality same as the original image is not also easy. So this article is contributed to those web programmers struggling to create thumbnail images using several logics. This article explains the two ways of creating thumbnail images, which we considered the best.

To upload images to the server, we need a File Upload control and a button control. Asp.Net simplifies the process of uploading images to the server with the FileUpload control. To start with, place a FileUpload control and a button control on your webpage. For readability, change the text of the button control as ‘Upload’.
Method 1:

In this method, we are going to use Size Structure class library. It is a .NET class library structure, stores an ordered pair of integers, normally the width and height of a rectangle. By using this Size Structure we are going to scale the original image, to its appropriate thumbnail size without any disturbances in the quality of the thumbnail image. Size structure class library is available in System.Drawing namespace.

To achieve this, we have a write a general method called ‘NewImageSize’. This method takes 3 parameters such as the original height, original width of the original image and the target thumbnail size you want to resize the original image.
public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
  Size NewSize; 
  double tempval; 

  if (OriginalHeight > FormatSize && OriginalWidth > FormatSize) 
    if (OriginalHeight > OriginalWidth) 
        tempval = FormatSize / Convert.ToDouble(OriginalHeight); 
        tempval = FormatSize / Convert.ToDouble(OriginalWidth); 

    NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight)); 
    NewSize = new Size(OriginalWidth, OriginalHeight); return NewSize;
By passing those parameters, the above method will be proportionately scale the original image and returns the exact size of the thumbnail. We can use this new size to create the thumbnail images and store it in the server.

In the click event of the Upload button, write the following code.
if (FileUpload1.PostedFile != null)
 string ImageName ="SampleImage.jpg";
 FileUpload1.SaveAs(Server.MapPath("Images\\") + ImageName);
 string ThumbnailPath = (Server.MapPath("ThumbnailImages\\") + ImageName;

 using (System.Drawing.Image Img =
      System.Drawing.Image.FromFile(Server.MapPath("Images\\") + ImageName))
        Size ThumbNailSize = NewImageSize(Img.Height, Img.Width, 150); 

        using (System.Drawing.Image ImgThnail =
            new Bitmap(Img, ThumbNailSize.Width,  ThumbNailSize.Height))
            ImgThnail.Save(ThumbnailPath, Img.RawFormat); 

Here we take the image path from the FileUpload control and save the original image inside “Images” folder. Then we declare another path to save the thumbnail image.

To know the original height and width of the Original Image, we have to create an Image instance and load it by using the ‘FromFile’ method. Passes the Height and Width to the NewImageSize method along with your desired Thumbnail size in pixel. In the above code, the thumbnail size is 150 pixels height and width.

So the proportionate thumbnail size will be returned to ThumbnailSize Size Structure. Now the Original Image and the size for the thumbnail is ready with us. Last we are going to create another Image object as ImgThnail, which is initialized as a BitMap Image with the Height and Width of the Thumbnail size. Now call the Save method of the ImgThnail object, to store the Thumbnail Image in its appropriate size and location. Finally, call Dispose method, this will release the all the resources used by the Image objects.

Method 2:

The second method is by using the GetThumbnailImage method of the Image class. This method returns the thumbnail image for the given original image. The syntax for this method is

public Image GetThumbnailImage
  int thumbnail_Width, 
  int thumbnail_Height, 
  delegate GetThumbnailImageAbort callback, 
  IntPtr callbackData

The GetThumbnailImage method takes 4 parameters such as the width of the thumbnail, height of the thumbnail image in pixels, an unused delegate and a handle or pointer that must be always Zero. This method retrieves the original image, creates a thumbnail by scaling the original image.

To create thumbnail by this method, first we to have to create a dummy delegate function, which always return false value. The syntax for the delegate function is as follows
public bool ThumbnailCallback()
  return false;

Then in the Upload button’s click event write the following code.

if (FileUpload1.PostedFile != null)
  string ImageName =”SampleImage.jpg”; 
  FileUpload1.SaveAs(Server.MapPath("Images\\") + ImageName); 

  string ThumbnailPath = (Server.MapPath("ThumbnailImages\\") + ImageName; 
  System.Drawing.Image.GetThumbnailImageAbort myCallback = 
        new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback); 

  using(System.Drawing.Image TargetImage = 
        System.Drawing.Image.FromFile(Server.MapPath("Images\\") + FileName)) 
      using (System.Drawing.Image Thumbnail = 
            TargetImage.GetThumbnailImage(100, 200, myCallback, IntPtr.Zero)) 
            Thumbnail.Save(Server.MapPath("Images\\") + ImageName); 

By using the FileUpload control’s Save method, we store the original image in the Server. Then we are creating a CallBack delegate by using GetThumbnailImageAbort method. This method provides a callback to the Delegate ThumbnailCallback, when the GetThumbnailImage stops its execution in a premature state. If this happens it will return a true value else it will return always false. Might be it is beyond the scope of this article, we shall leave it here.

Next we are create 2 Image objects such as TargetImage and Thumbnail. The first one TargetImage is to retrieve the original Image and the second Thumbnail is to create Thumbnail Image. Call the GetThumbnailImage method of the Thumbnail object to create a thumbnail image by passing the parameters such as width, height, dummy delegate callback and a handle with Zero value. By calling the Save method of the Thumbnail Image object, we can create thumbnail. Finally we call the Dispose method, to release the resources used by our Image objects.

Point to Remember:

If you look carefully in the above block of codes in both the methods, we are creating the all Image objects within a ‘using’ statement. What does this really do?

The answer is simple. The using statement ensures that Dispose method is called without failure. Eventhough we don’t call Dispose explicitly, it is enough to enclose the statement with the using statement. The purpose of using it here is that we create Image objects and access Images that is stored in the server location. So after using the Images, if do not release it completely than it will create some Exceptions. In other case, if an Exception occurs in intermediate of the Image processing, then the .NET framework cannot release the resources used by the Image object. It will raise an Exception as follows

The process cannot access the file because it is being used by another process.

So when you enclose the Image objects between using statement, then the Images and other files used within the using statement block will be released perfectly even though exception is raised. So we always recommend you to use using statement.

The information provided in this article is only simple methods of creating thumbnail images at run-time or on fly. But there can be other methods, which will create thumbnail with simple technique and excellent quality. So we request our readers to provide them to us, so as to help other novice Asp.Net developers.
Viewer's Comments
Posted by KIRANTEJ on 7/7/2008 6:08:16 AM
send more codes
Posted by jk on 8/14/2008 2:23:55 AM
I want to show image in form at run time, when we upload the image and show in imagebox?
Posted by kji on 8/18/2008 4:05:00 AM
send full code
Posted by adithyadugyala on 9/11/2008 6:45:49 AM
hi can u plz send me the complete code of this article
Posted by karthick on 9/25/2008 12:59:59 AM
hey i want more codes plz..........
Posted by Rajasekar on 11/7/2008 12:27:15 AM
fine ,but one error occured (A generic error occurred in GDI+. )
Posted by dilip maurya on 11/17/2008 2:01:27 AM
hi,please help me it show following error (A generic error occurred in GDI+. )
Posted by Prasad on 11/20/2008 1:33:48 AM
Hi, Can you send me complete source code for Method II Thanks
Posted by Addy on 12/8/2008 3:31:15 AM
Hi, Have Test your code with GIF. Plz Test with GIF. I Have also developed similar code for generate thumbnail but it gives bad quality GIF If you find any solution then plz tell me thank you you done Good Job
Posted by Nathanael Jones on 2/3/2009 10:03:22 AM
Don't use GetThumbnailImage as directed - it tries to use the embedded images in Jpegs and will generate terribly blurry images for some cameras. Use DrawImage instead, with HighQuality on all 4 settings. I'd recommend looking at [ this module]. It makes resizing a single method call, in addition to the terribly convenient querystring syntax. It's open-source, too :D.
Posted by Nathanael Jones on 2/3/2009 10:04:29 AM
Hey, the comment system crashes on HTML. Not sure what the linking syntax is :)
Posted by hamzhdawod on 3/1/2009 6:23:00 AM
please send full code
Posted by Tamil on 3/11/2009 12:38:16 AM
hi i need whole code please send me ,its very useful for me.
Posted by Nishant makvana on 3/31/2009 2:46:01 AM
MemoryStream imgStream = new MemoryStream(byte[] imgbinary, 0, imgbinary.length); System.Drawing.Image img = System.Drawing.Image.FromStream(imgStream); img.Save(Server.MapPath("~/destinationfolder/sample.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg); Image1.ImageUrl = "~/destinationfolder/sample.jpg"; Now you can display image in image control without using handler or another page Display system.drwing.image in ImageControl
Posted by Harpreet Singh Gill on 6/24/2009 7:57:14 AM
Nice example, Its helped me very much Thanks
Posted by Kiran on 9/22/2009 7:32:42 AM
Thanks for the article...
Posted by Davide on 10/3/2009 9:41:54 AM
needed here
Posted by ishita on 4/5/2010 4:25:28 AM
Posted by sao xiong on 5/24/2010 4:07:16 PM
Posted by Ranjan Chakrabarti on 10/27/2010 7:08:10 AM
Posted by Rumesh Sruvastav on 1/12/2012 4:44:17 AM
Really this is a good article, which helps a lot for beginners as me as well as developer. Thanks for sharing with us. Check out this helpful link too its also having nice post with wonderful explanation on image control in,....... Thanks everyone for precious post!!
 Rating & Comments
A word 'Excellent' means lot to the author of this article. You can give comments about this article but not the author.
Rate this Article:
Email Id:  
We never display your email id anywhere.
Comment/Question: Max. 500 letters
Seventy plus Three Equals To
Sponsored by
Many .NET teams are underperforming, is yours?
Sexy Web Design - Free 71 Page Preview!
Backup and Recovery Best Practices for Microsoft SQL Server 2005