A thumbnail is a small sized image. creating a thumbnail using. net is extremely simple. in this article, we will expose e 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;
}
}
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 ");
}
}
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 );
}
Run the application, select the image and click on the generate button. The preview will be similar to the image displayed below:
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 wocould encourage you to try out these ideas.