Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

A FileDialog.Filter generator for all supported images

4.85/5 (14 votes)
18 Sep 2011CPOL 61.3K  
Recently, I had to write a quick app to load images into a database, and wanted to restrict the file type to just images. You can do this with the OpenFileDialog.Filter property, but it is a pain working out what file extensions to permit.
Recently, I had to write a quick app to load images into a database, and wanted to restrict the file type to just images. You can do this with the OpenFileDialog.Filter property, but it is a pain working out what file extensions to permit. This method returns a Filter compatible string built from the image formats the current system understands.

C#
/// <summary>
/// Get the Filter string for all supported image types.
/// This can be used directly to the FileDialog class Filter Property.
/// </summary>
/// <returns></returns>
public string GetImageFilter()
    {
    StringBuilder allImageExtensions = new StringBuilder();
    string separator = "";
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
    Dictionary<string, string> images = new Dictionary<string, string>();
    foreach (ImageCodecInfo codec in codecs)
        {
        allImageExtensions.Append(separator);
        allImageExtensions.Append(codec.FilenameExtension);
        separator = ";";
        images.Add(string.Format("{0} Files: ({1})", codec.FormatDescription, codec.FilenameExtension),
                   codec.FilenameExtension);
        }
    StringBuilder sb = new StringBuilder();
    if (allImageExtensions.Length > 0)
        {
        sb.AppendFormat("{0}|{1}", "All Images", allImageExtensions.ToString());
        }
    images.Add("All Files", "*.*");
    foreach (KeyValuePair<string, string> image in images)
        {
        sb.AppendFormat("|{0}|{1}", image.Key, image.Value);
        }
    return sb.ToString();
    }


This returns a string that (on my system) is:

All Images|*.BMP;*.DIB;*.RLE;*.JPG;*.JPEG;*.JPE;*.JFIF;*.GIF;*.TIF;*.TIFF;*.PNG|
BMP Files: (*.BMP;*.DIB;*.RLE)|*.BMP;*.DIB;*.RLE|
JPEG Files: (*.JPG;*.JPEG;*.JPE;*.JFIF)|*.JPG;*.JPEG;*.JPE;*.JFIF|
GIF Files: (*.GIF)|*.GIF|
TIFF Files: (*.TIF;*.TIFF)|*.TIF;*.TIFF|
PNG Files: (*.PNG)|*.PNG|
All Files|*.*


Suitable for loading directly into the OpenFileDialog or SaveFileDialog Filter property.

[edit]Typos, and abstract trucated by the system. Abstract shorted, and added to main text body - OriginalGriff[/edit]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)