How to Create Thumbnail Images in C# and VB.NET

Posted by: Suprotim Agarwal , on 4/12/2008, in Category WinForms & WinRT
Views: 111803
Abstract: 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.
How to Create Thumbnail Images in C# and VB.NET
 
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:
Step 1: Open Visual Studio 2005/2008. File > New > Project > Visual C# or Visual Basic > Windows Application. Enter the name of the application and click Ok.
Step 2: Drag and drop a label, 2 button controls and an OpenFileDialog component to the form. Rename them as follows:
Label1 – lblFile
Button1 – btnOpen
Button2 – btnGenerateThumbnail
TextBox – txtFileNm
OpenFileDialog – Set the Filter to ‘JPG Files|*.jpg’
Step 3: On the ‘btnOpen’ click, display the File Open dialog box and accept the selected .jpg file in the txtFileNm textbox.
C#
        private void btnOpen_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtFileNm.Text = openFileDialog1.FileName;
            }
        }
VB.NET
            Private Sub btnOpen_Click(ByVal sender As Object, ByVal e As EventArgs)
                  If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
                        txtFileNm.Text = openFileDialog1.FileName
                  End If
            End Sub
Step 4: Next, on the ‘btnGenerateThumbnail’ click, add the following code:
C#

// Declare a class level variable

Image imgThumb = null;

        private void btnGenerateThumbnail_Click(object sender, EventArgs e)
        {
            try
            {
                Image image = null;
                // Check if textbox has a value
                if (txtFileNm.Text != String.Empty)
                    image = Image.FromFile(txtFileNm.Text);
                // Check if image exists
                if (image != null)
                {
                    imgThumb = image.GetThumbnailImage(100, 100, null, new IntPtr());
                    this.Refresh();
                }
            }
            catch
            {
                MessageBox.Show("An error occured");
            }
        }
VB.NET

' Declare a class level variable

Dim imgThumb As Image = Nothing

            Private Sub btnGenerateThumbnail_Click(ByVal sender As Object, ByVal e As EventArgs)
                  Try
                        Dim image As Image = Nothing
                        ' Check if textbox has a value
                        If txtFileNm.Text <> String.Empty Then
                              image = Image.FromFile(txtFileNm.Text)
                        End If
                        ' Check if image exists
                        If Not image Is Nothing Then
                              imgThumb = image.GetThumbnailImage(100, 100, Nothing, New IntPtr())
                              Me.Refresh()
                        End If
                  Catch
                        MessageBox.Show("An error occured")
                  End Try
            End Sub
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 :
Width, in pixel of the thumbnail image that is to be generated
Height, in pixel of the thumbnail image that is to be generated
Callback, a Image.GetTumbnailImageAbort delegate to prematurely cancel execution
CallbackData, of type IntPtr to represent a pointer or a handle.
Step 5: The final step is to add the Paint event which is called using this.Refresh() in the button click. The thumbnail image is drawn on the form.
C#
        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            if(imgThumb != null)
            e.Graphics.DrawImage(imgThumb,30, 20, imgThumb.Width, imgThumb.Height);
        }
VB.NET
            Private Sub Form1_Paint(ByVal sender As Object, ByVal e As PaintEventArgs)
                  If Not imgThumb Is Nothing Then
                  e.Graphics.DrawImage(imgThumb,30, 20, imgThumb.Width, imgThumb.Height)
                  End If
            End Sub
Run the application, select the image and click on the Generate button. The preview will be similar to the image displayed below :
Generate Thumbnail
You can actually extend this example to 'save' the generated thumbnails. Something like a ‘Thumbnail Creator’ program. You can loop through a folder containing images and generate thumbnail images for all the images in the folder. I would encourage you to try out these ideas. 
I hope this article was useful and I thank you for viewing it.
If you liked the article,  Subscribe to my RSS Feed.
 
Give me a +1 if you think it was a good article. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Suresh on Monday, April 14, 2008 4:13 AM
Hi,

Where have you declared imgThumb ?

Thanks,
Suresh
Comment posted by Suprotim Agarwal on Monday, April 14, 2008 9:23 AM
Thanks so much Suresh. I have added the code.
Comment posted by Raja on Wednesday, April 30, 2008 3:41 AM
Creating thumbnail for web based application, this articles seems very good.

http://dotnetfunda.com/articles/article63.aspx (Dynamically generating thumbnail images in ASP.NET with C# without affecting initial page load time)
Comment posted by nivedita on Tuesday, August 5, 2008 4:32 AM
i hv tried this code in web application.
> line (in your code)
image = Image.FromFile(txtFileNm.Text);
i hv used,
string fn=System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);

its not giving me "FromFile" method.

thanks..

i'm not getting "FromFile" method.
Comment posted by Arvind yadav on Saturday, October 4, 2008 7:05 AM
Please send the code for web application in asp.net 2.0(c#).

Thanks in advance.
Comment posted by Nithya k on Wednesday, October 8, 2008 6:52 AM
i have done this application thank u very much
Comment posted by msatyagupt on Monday, March 23, 2009 5:47 AM
Suppose I have a XML file like

<Messages>
<Msg id="001" Value="This is first Message></Msg>
<Msg id="002" Value="This is Second Message></Msg>
<Msg id="003" Value="This is third Message></Msg>
</Messages>

I want to read the Msg Value from a function whenever a pass its id, when i pass id 001 it will show "This is first message"

Is it possible, Help me,

thanx in advance

Comment posted by msatyagupt on Monday, March 23, 2009 6:04 AM
i want to display an image in image control from the database. i have displayed it by memorystream in seperate windows but i want to display it in image control of same window

any help will be appreciated

thanx in advance
Comment posted by Suprotim Agarwal on Tuesday, March 24, 2009 3:30 AM
msatyagupt: Check this article - http://www.dotnetcurry.com/ShowArticle.aspx?ID=129
Comment posted by msatyagupt on Wednesday, March 25, 2009 3:01 AM
Thanks so much Suprotim. This article helped me. Now I am able to display image in my control. Thanks once again.
Comment posted by Spangjet on Thursday, March 26, 2009 7:36 PM
Very Nice article. Clear layout and well explained. How would I extend this to loop through files in a folder to make a simple batch thumbnailer? Something real simple - destination folder with thumbnails of the same name.
Comment posted by tony on Sunday, May 17, 2009 5:17 PM
Its very interesting but it doesn't work in my application.
The image doesn't appear.
Can you help me, please.
Comment posted by ashish bisen on Tuesday, May 19, 2009 4:57 AM
I have used this code in web application but it is not working .....
How can use this in web application to create a thubnail images. will you send some code for this??
Comment posted by ashish on Tuesday, May 19, 2009 4:57 AM
can any one done this in web application
Comment posted by vbdotwhat on Saturday, January 23, 2010 7:17 AM
Comment posted by Spangjet  on Thursday, March 26, 2009 7:36 PM      
Very Nice article. Clear layout and well explained. How would I extend this to loop through files in a folder to make a simple batch thumbnailer? Something real simple - destination folder with thumbnails of the same name.


private void Search(string dir)
        {
            //Searched the pc for images.
            try
            {
                foreach (string file in Directory.GetFiles(dir))
                {
                    
                    if (IsPic(file))
                    {
                        //covert and move to thumb folder
                    }
                }
                foreach (string folder in Directory.GetDirectories(dir))
                {
                    Search(folder);
                }
            }
            catch (Exception e)
            {
            }
        }
Comment posted by S.williams on Thursday, July 22, 2010 10:19 PM
I've tried this code in an AutoCAD vb.net application and it gives me an "out of memory" error. Do these "thumbnails" refer to just an image file (JPG, BMP, etc.) or any kind of file like an AutoCAD file that has a thumbnail image embedded? Also, I can't simply declare something as an "Image" because it treats it as an AutoCAD Image and doesn't offer the same methods. Help?
Comment posted by jean on Thursday, March 10, 2011 4:07 AM
It doesn't work for my application. i'm using visual studio 2008.. can any one help?
Comment posted by shahid on Wednesday, July 25, 2012 12:06 AM
is there any way to convert MS Word document to thumbnail without having MS world installed on machine.My requirement is that i have to create Document preview functionality that will preview document file as image.
Any help will be appreciated.
Comment posted by Stewart Grainger on Thursday, August 23, 2012 5:29 AM
Why are my files larger in file size than the original, what about compression and cropping?

Regards
My G
Comment posted by Muthu on Saturday, August 25, 2012 1:07 AM
this.refresh() is not calling the Form1_Paint function.
Comment posted by shameeer ali on Saturday, September 1, 2012 4:11 AM
nice article to create thumbnails from a image..

but, i have a doubt..
once video has been uploaded in server, at that time the thumbnail should be created...

can you provide the coding for creating the thumbnail from a video file (like .flv), using c#..

thanks
shameer ali
Comment posted by JC on Wednesday, September 19, 2012 8:55 PM
Thanks so much.  Only took me 10 minutes and it works like a charm.
Comment posted by sam on Monday, February 11, 2013 6:22 AM
thanks for comments
I cant create because Form1_paint is not generated!
please explain more
thanks
Comment posted by marrisa on Wednesday, June 26, 2013 1:41 AM
useful methods! thank you for sharing. however, IMO, it's kind of complicated, i would prefer to some simple and easy code. just like that stated on the <a href="http://www.rasteredge.com/how-to/vb-net-imaging/thumbnail-creating/">thumbnail create</a>
Comment posted by James Dawson on Tuesday, November 5, 2013 2:32 PM
Hi,

I was wondering if there is and if you know of the reference to select in Excel VBA to make the Image.GetThumbnailImage method. I would like to do this in an Excel macro.

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel