Saturday, December 4, 2010

Create Thumbnail Images In C#

A thumbnail is a small sized image. Creating a thumbnail using .NET is extremely simple. In this article, we will explore how to create a thumbnail image and display the thumbnail in our application. Follow these steps:
  1. First Add Windows Form In your Application. After that Drag & drop 1 Label ,  1 TextBox , 2 Buttons , 1 PictureBox & 1 OpenfileDialogBox Controls From Toolbox. Now change all the names of the controls that mention belowed.
  2.    1: TextBox Name = 'txtPath'
       2: 1st Button Name = 'btnOpen'
       3: 2nd Button Name = 'btnGenerate'
       4: PictureBox Name = 'picthumb' And Set Height & Width = 100,100
  3. After renaming All the controls On the ‘btnOpen’ click display the File Open dialog box and accept the selected .jpg file in the ’txtPath’ textbox.
  4.    1: private void btnOpen_Click(object sender, EventArgs e)
       2:         {
       3:             if (openFileDialog1.ShowDialog().ToString() == "OK")
       4:             {
       5:                 txtPath.Text = openFileDialog1.FileName;   
       6:             }
       7:         }
  5. Next, on the ‘btnGenerate’ click, add the following code:
  6.    1: private void btnGenerate_Click(object sender, EventArgs e)
       2:         {
       3:             Image Img = null;
       4:             Img = Image.FromFile(txtPath.Text);
       5:             Image ImgThumbs = Img.GetThumbnailImage(100, 100, null, new IntPtr());
       6:             if (ImgThumbs != null)
       7:             {
       8:                 picthumb.Image = ImgThumbs;
       9:             }   
      10:         }
    The code creates an Image object from the image supplied in the textbox. Using the Image.GetThumbnailImage(), the code then creates a thumbnail image with a size of 100*100.
    The Image.GetThumbnailImage() takes in four arguments :
       1: Width : in pixel of the thumbnail image that is to be generated
       2: Height : in pixel of the thumbnail image that is to be generated
       3: Callback : a Image.GetTumbnailImageAbort delegate to prematurely cancel execution
       4: CallbackData : of type IntPtr to represent a pointer or a handl