Use an OpenFileDialog's Filter property to let the user open different kinds of image files in C#

This example is mostly intended to make it easier to find these filters. I use them a lot and it's a pain to have to recreate them every time I need them. This example's buttons use these two filters:

    Bitmaps|*.bmp|PNG files|*.png|JPEG files|*.jpg|GIF files|*.gif|
        TIFF files|*.tif|Image files|*.bmp;*.jpg;*.gif;*.png;*.tif|All files|*.*

    Image files|*.bmp;*.jpg;*.gif;*.png;*.tif|All files|*.*

When you click a button, the program sets the OpenFileDialog's Filter property to the appropriate value and then displays it. For example, the following code shows how the program responds when you click the second button.

// Use only the Image files and All files filters.
private void btnAllImages_Click(object sender, EventArgs e)
{
    ofdImage.Filter = "Image files|*.bmp;*.jpg;*.gif;*.png;*.tif|All files|*.*";
    ofdImage.FilterIndex = 0;
    if (ofdImage.ShowDialog() == DialogResult.OK)
    {
        try
        {
            picImage.Image = new Bitmap(ofdImage.FileName);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

This filter lets the user pick from two kinds of files: image files (bmp, g, gif, png, or tif) or all files. The code sets the dialog's Filter property appropriately and sets FilterIndex = 0 to select the first filter. It then displays the dialog.

If the user selects a file and clicks OK, the program displays the file in the PictureBox named picImage. The program uses a try catch block to protect itself in case the selected file isn't an image file. (So I could test the "All files" filter by selecting a non-image file.)

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.