Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » Windows Controls C# » Image viewer user control with preview capability

Image viewer user control with preview capability

This article discusses the construction of an image viewer user control that may be used to display images from a directory containing a collection of image files. The control displays the previous and next images in the file along with the current image.

Author Rank :
Page Views : 12819
Downloads : 660
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
ImageViewerUserControl_CS.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

Introduction:

This article discusses the construction of an image viewer user control that may be used to display images from a directory containing a collection of image files. The control displays the previous and next images in the file along with the current image. The current image may be opened from the user control into the default image application on the user's machine based upon that machine's file associations. Image thumbnails are used to supply the previous, current, and next images from the directory. As shown in the demonstration, the user control could be added to an application where you might need to allow users to preview or visually scan images prior to opening them up for viewing or edit.



Figure 1: Image Viewer User Control Loaded into a Test Application



Figure 2: Opening an Image into the Default Image Application (Microsoft Office Picture Manager shown)

Getting Started:

In order to get started, unzip the included project and open the solution in the Visual Studio 2005 environment. There are two project contained in the solution. ImageViewer is the first project and it is control library project containing a single user control. The second project is a test application which displays a single form used to contain the user control.
In the solution explorer, you should note these files:



Figure 3: Solution Explorer

The Image Viewer User Control (ImageViewer.cs)

The Image Viewer user control contains everything necessary to browse to the image folder and to view the current, next, and previous images. The control itself contains a text box and browse button used to open a folder browser dialog box; when the user navigates to the desired folder and selects it, the path the folder will be shown in the textbox control and the browse button click event handler will trigger the collection of all of the image files contained in the selected folder and will start up the display of the images. The control contains three picture boxes used to display the previous, current, and next images. The previous and next images are accompanied by two buttons used to move backwards and forwards through the image collection. The paths to each of the image files are contained in an array list and an integer value with class scope is used to maintain the current position within that array list. 

If you'd care to open the code view up in the IDE you will see that the code file begins with the following using statements; most included are per the default configuration but System.IO was added to support the directory operations used within the code.

using System;<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

using System.Collections;

using System.ComponentModel;

using System.Drawing;

using System.Data;

using System.IO;

using System.Text;
using System.Windows.Forms;

Following the imports, the namespace and class are defined and a constructor added as are a collection of local member variables used to maintain the folder path, the image file paths (in an array list), the image list position, and the images themselves (previous, current, and next). 

namespace
ImageViewer

    /// <summary>

    /// A user control used to allow previewing

    /// the previous, current and next images in a

    /// folder containing image files

    /// </summary>

    public partial class ImageViewer : UserControl

    {

        // private member variables

        private string mFolder;

        private ArrayList mImageList;

        private int mImagePosition;

        private Image mPreviousImage;

        private Image mCurrentImage;

        private Image mNextImage; 

        /// <summary>

        /// Default constructor

        /// </summary>

        public ImageViewer()

        {

            InitializeComponent();

        }

Next up is the user control's load event handler; this demonstration does not do anything in the load event but you may wish to use this handler to set a default image folder or something such as that if need be.

        /// <summary>

        /// Load Event for User Control

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void UserControl1_Load(object sender, EventArgs e)

        {

            // do nothing on load

        }

The next section of the code is the browse button click event handler. In this section of the code, the handler opens the folder browser dialog box which the user may then use to set the path to the image folder. Once the folder has been set, the handler loops through that folder and locates all bitmap, jpeg, and gif files; the file paths any image files found are added to an array list (bitmaps, gifs, and jpegs). Once the array list is populated with the files paths, the click event handler wraps up but setting the list index position to zero and then it calls the SetImages method which sets up the current, previous, and next images into the appropriate picture box. The code is annotated and should be easy enough to follow:

        /// <summary>

        /// Set the image folder location.

        ///

        /// Store all of the image file names into the

        /// Image List (mImageList) and then load the

        /// initial images

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnBrowse_Click(object sender, EventArgs e)

        {

            // Label the folder browser dialog

            this.folderBrowserDialog1.Description = "Select the image directory.";

 

            // disable create folder feature of folder browser

            this.folderBrowserDialog1.ShowNewFolderButton = false;

 

            // display the folder browser

            DialogResult result = folderBrowserDialog1.ShowDialog();

            if (result == DialogResult.OK)

            {

                // on okay, set the image folder to the

                // folder browser's selected path

                mFolder = folderBrowserDialog1.SelectedPath;

                if (!String.IsNullOrEmpty(mFolder))

                {

                    txtImageDirectory.Text = mFolder;

                }

            }

            else

            {

                // exit if the user cancels

                return;

            }

 

            // initialize the image arraylist

            mImageList = new ArrayList();

 

            // loop through the image directory

            // and find all of the image files;

            // add the found files to the image

            // list - add other image types if

            // necessary

            DirectoryInfo dir = new DirectoryInfo(mFolder);

            foreach (FileInfo f in dir.GetFiles("*.*"))

            {

                switch (f.Extension.ToUpper())

                {

                    case ".JPG":

                        mImageList.Add(f.FullName);

                        break;

                    case ".BMP":

                        mImageList.Add(f.FullName);

                        break;

                    case ".GIF":

                        mImageList.Add(f.FullName);

                        break;

                    default:

                        break;

                }

            }

 

            // set the starting position to 0

            // and call the set images method

            // to load the pictures

            mImagePosition = 0;

            SetImages();

        }

The next bit of code is the SetImages function; this function is used to set the images for each of the picture boxes (previous, current, and next image). This code creates thumbnails the images stored as file paths in the images array list and then sets the picture boxes to display the thumbnails rather than the full images. The code is written to respond differently when hitting the limits of the array list used to store the file paths to the actual images; at the limits, the previous or next images will be blanked.

Further, the code clears out the images once they picture boxes are set, and garbage collection is called to clean it up each time the function is called. I found that, without garbage collection, the control would through an out of memory exception when scanning through large numbers of images in one setting. Again, this code is annotated and should be easy enough to follow:

        /// <summary>

        /// This function is used to set the previous,

        /// current, and next images into the

        /// correct picture boxes

        /// </summary>

        private void SetImages()

        {

            // clear any existing images

            // memory will be an issue if

            // cycling through a large

            // number of images

            mPreviousImage = null;

            mNextImage = null;

            mCurrentImage = null;

 

            // set the previous image

            if (mImagePosition > 0)

            {

                try

                {

                    // set delegate

                    Image.GetThumbnailImageAbort prevCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);

 

                    // get the previous image

                    Bitmap prevBmp = new Bitmap(mImageList[mImagePosition - 1].ToString());

 

                    // thumbnail the image to the size

                    // of the picture box

                    mPreviousImage =prevBmp.GetThumbnailImage(160, 100,prevCallback, IntPtr.Zero);

 

                    // set the picture box image

                    picPreviousImage.Image = mPreviousImage;

 

                    // clear everything out

                    prevBmp = null;

                    prevCallback = null;

                    mPreviousImage = null;

                }

                catch

                {

                    //stall if it hangs, the user can retry

                }

            }

            else

            {

                // at the limit; clear the

                // image

                picPreviousImage.Image = null;

            }

           

            // set current image

            if (mImagePosition < mImageList.Count)

            {

                try

                {

                    // set delegate

                    Image.GetThumbnailImageAbort currentCallback =new Image.GetThumbnailImageAbort(ThumbnailCallback);

 

                    // get the current image

                    Bitmap currentBmp = new Bitmap(mImageList[mImagePosition].ToString());

 

                    // thumbnail the image to the size

                    // of the picture box

                    mCurrentImage =currentBmp.GetThumbnailImage(320, 200,currentCallback, IntPtr.Zero);

 

                    // set the picture box image

                    picCurrentImage.Image = mCurrentImage;

 

                    // clear everything out

                    currentBmp = null;

                    mCurrentImage = null;

                    currentCallback = null;

                }

                catch

                {

                    //stall if it hangs, the user can retry

                }

            }

           

            // set next image

            if (mImagePosition < mImageList.Count-1)

            {

                try

                {

                    // set delegate

                    Image.GetThumbnailImageAbort nextCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback);

 

                    // get the next image

                    Bitmap nextBmp = new Bitmap(mImageList[mImagePosition + 1].ToString());

 

                    // thumbnail the image to the size

                    // of the picture box

                    mNextImage = nextBmp.GetThumbnailImage(160, 100, nextCallback,IntPtr.Zero);

 

                    // set the picture box image

                    picNextImage.Image = mNextImage;

 

                    // clear everything out

                    nextBmp = null;

                    nextCallback = null;

                    mNextImage = null;

                }

                catch

                {

                    //stall if it hangs, the user can retry

                }

            }

            else

            {

                // at the limit; clear the

                // image

                picNextImage.Image = null;

            }  

            // call for garbage collection

            GC.Collect();

        }

The next bit of code is the code called if the thumbnail image attempt aborts; this is required by the method used to generate the thumbnail. 

        /// <summary>

        /// Thumbnail image abort target

        /// </summary>

        /// <returns></returns>

        public bool ThumbnailCallback()

        {

            return false;

        }

The previous image button click event handler is next up; it is used to update the image position within the array list and to recall the SetImages method when the index position is updated:

        /// <summary>

        /// Set the image position and reset all of

        /// the images when the previous image

        /// button is clicked

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnPreviousImage_Click(object sender, EventArgs e)

        {

            if (mImagePosition >= 0 && picPreviousImage.Image != null)

            {

                mImagePosition;

                SetImages();

            }

        }

The next image button click event handler is next up; it is used to update the image position within the array list and to recall the SetImages method when the index position is updated:
 

        /// <summary>

        /// Set the image position and reset all

        /// of the images when the next image

        /// button is clicked

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnNextImage_Click(object sender, EventArgs e)

        {

            if (mImagePosition <= (mImageList.Count - 2))

            {

                mImagePosition++;

                SetImages();

            }

        }

The last method is used to open the current image into the default image viewing application as based upon the machine's file associations. This method merely calls the process start function and passes it the file path to the current image file.

        /// <summary>

        /// Open the current image using the default

        /// program per the user's file associations

        /// </summary>

        /// <param name="sender"></param>

        /// <param name="e"></param>

        private void btnOpenImage_Click(object sender, EventArgs e)

        {

            System.Diagnostics.Process.Start(

mImageList[mImagePosition].ToString());

        }

The Text Form (Form1.cs)

The test form contained with the test application contains a single instance of the Image Viewer user control; the form itself has no specific code leaving nothing to report here. The test application was set as the start up project and, when executed, the test form opens up and displays the user control. 

Summary

This solution provides a user control that may be used to provide a user interface that may be helpful if the user of an application will need to browse for image files. The user control provides the controls necessary to browse for a folder containing images along with the means to preview the currently selected, previous, and next images. Through the control, the end user may browse through all of the image files contained in the folder and, if desired, may open on the images into a new application.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Scott Lysle
Freelance software developer residing in Alabama. Bachelors, Masters Degrees from Wichita State University. I spent the first half of my career working on aircraft controls and displays and in that time I worked on the cockpits for the OH-58 AHIP, the AH-1W, the V-22, the F-22, the C-130J, the C-5 AMP, AWACS, JPATS, and a few others. Since 1997 I have been largely involved with Windows and web development, GIS application development, consumer electronics development (embedded linux/java), but still sometimes work on aircraft and military projects, the most recent of which was the presidential transport helicopter. I tend to work primarily with C/C++, Java, VB, and C#.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
6 Months Free & No Setup Fees ASP.NET Hosting!
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.