Display thumbnails for image files in a directory in C#

[display thumbnails]

This example shows how to display thumbnails for the images in a directory. It displays a tooltip when the mouse hovers over a picture and it opens the image file in the default application if you double-click on an image.

This program is actually much easier than you might think because controls do all of the work of arranging the pictures. The program contains a (green) FlowLayoutPanel with its AutoScroll property set to true. The program only needs to drop PictureBox controls onto it and it automatically arranges them and displays scroll bars if necessary.

The following code shows how the program displays thumbnails when the directory in the TextBox changes.

// PictureBoxes we use to display thumbnails.
private List<PictureBox> PictureBoxes = new List<PictureBox>();

// Thumbnail sizes.
private const int ThumbWidth = 100;
private const int ThumbHeight = 100;

// Display thumbnails for the selected directory.
private void txtDirectory_TextChanged(object sender, EventArgs e)
{
    // Delete the old PictureBoxes.
    foreach (PictureBox pic in PictureBoxes)
    {
        //pic.Click -= PictureBox_Click;
        pic.DoubleClick -= PictureBox_DoubleClick;
        pic.Dispose();
    }
    flpThumbnails.Controls.Clear();
    PictureBoxes = new List<PictureBox>();

    // If the directory doesn't exist, do nothing else.
    if (!Directory.Exists(txtDirectory.Text)) return;

    // Get the names of the files in the directory.
    List<string> filenames = new List<string>();
    string[] patterns =
        { "*.png", "*.gif", "*.jpg", "*.bmp", "*.tif" };
    foreach (string pattern in patterns)
    {
        filenames.AddRange(Directory.GetFiles(txtDirectory.Text,
            pattern, SearchOption.TopDirectoryOnly));
    }
    filenames.Sort();

    // Load the files.
    foreach (string filename in filenames)
    {
        // Load the picture into a PictureBox.
        PictureBox pic = new PictureBox();

        pic.ClientSize = new Size(ThumbWidth, ThumbHeight);
        pic.Image = new Bitmap(filename);

        // If the image is too big, zoom.
        if ((pic.Image.Width > ThumbWidth) ||
            (pic.Image.Height > ThumbHeight))
        {
            pic.SizeMode = PictureBoxSizeMode.Zoom;
        }
        else
        {
            pic.SizeMode = PictureBoxSizeMode.CenterImage;
        }

        // Add the DoubleClick event handler.
        //pic.Click += PictureBox_Click;
        pic.DoubleClick += PictureBox_DoubleClick;
        
        // Add a tooltip.
        FileInfo file_info = new FileInfo(filename);
        tipPicture.SetToolTip(pic, file_info.Name +
            "\nCreated: " +
            file_info.CreationTime.ToShortDateString() +
            "\n(" + pic.Image.Width + " x " +
            pic.Image.Height + ") " +
            ToFileSizeApi(file_info.Length));
        pic.Tag = file_info;

        // Add the PictureBox to the FlowLayoutPanel.
        pic.Parent = flpThumbnails;
    }
}

This code defines the List of PictureBox controls that it uses to display images. It also defines constants ThumbWidth and ThumbHeight, which determine the thumbnail size.

The txtDirectory_TextChanged does most of the work. First it removes the DoubleClick event handler from any existing PictureBox controls and disposes of them. It removes all of the child controls from the flpThumbnails FlowLayoutPanel and resets the PictureBoxes list.

Next the code uses Directory.Exists to see if the directory entered in the TextBox exists and returns if it doesn’t. This happens, for example, if you are typing in the TextBox and haven’t finished entering the directory’s name.

The code then loops over an array of file patterns looking for png, gif, jpg, and other image file formats. For each format, the code uses the Directory.GetFiles method to find files matching the pattern. That method returns an array of file names. The code uses the filenames list’s AddRange method to add all of the files it found to the list. After finding the files that match all of the patterns, the program sorts the filenames list.

Now the program loops through the file names. For each file, it creates a PictureBox, sets its size to the right thumbnail size, and loads the corresponding file into the PictureBox control’s Image property.

Next, if the image is larger than the PictureBox, the program sets the PictureBox control’s SizeMode property to Zoom so it displays it as large as possible without distorting it. If the image is smaller than the PictureBox, the program sets SizeMode to CenterImage so it displays the image at full scale centered in the control.

The code sets the PictureBox_DoubleClick event handler (shown shortly) to catch the control’s DoubleClick event and adds a tooltip describing the image. Finally the code sets the PictureBox control’s Parent property to the FlowLayoutPanel so the PictureBox is displayed inside the FlowLayoutPanel.

The following code shows the PictureBox_DoubleClick event handler that executes when you double-click a PictureBox.

// Open the file.
private void PictureBox_DoubleClick(object sender, EventArgs e)
{
    // Get the file's information.
    PictureBox pic = sender as PictureBox;
    FileInfo file_into = pic.Tag as FileInfo;

    // "Start" the file.
    Process.Start(file_into.FullName);
}

This code converts the sender parameter into the PictureBox that was double-clicked. It converts that control’s Tag property into the FileInfo that represents the correponding file. It then calls the System.Diagnostics.Process.Start method to “invoke” the file. That makes the computer open the file with the default application associated with the file’s type.

Notice how the program makes controls do most of the graphical work. The FlowLayoutPanel automatically arranges the pictures and displays scroll bars if necessary so you don’t have to. The PictureBox controls’ ScaleMode properties size the images appropriately without distorting them. All the code really does is list the files and create the PictureBox controls.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls, graphics, image processing and tagged , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *