This method automatically creates a filter for the OpenFileDialog
. It uses the informations of the image decoders supported by Windows. It also adds information of "unknown" image formats (see default
case of the switch
statement).
private static string SupportedImageDecodersFilter()
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
string allExtensions = encoders
.Select(enc => enc.FilenameExtension)
.Aggregate((current, next) => current + ";" + next)
.ToLowerInvariant();
var sb = new StringBuilder(500)
.AppendFormat("Image files ({0})|{1}", allExtensions.Replace(";", ", "),
allExtensions);
foreach (ImageCodecInfo encoder in encoders) {
string ext = encoder.FilenameExtension.ToLowerInvariant();
// ext = "*.bmp;*.dib;*.rle" descr = BMP
// ext = "*.jpg;*.jpeg;*.jpe;*.jfif" descr = JPEG
// ext = "*.gif" descr = GIF
// ext = "*.tif;*.tiff" descr = TIFF
// ext = "*.png" descr = PNG
string caption;
switch (encoder.FormatDescription) {
case "BMP":
caption = "Windows Bitmap";
break;
case "JPEG":
caption = "JPEG file";
break;
case "GIF":
caption = "Graphics Interchange Format";
break;
case "TIFF":
caption = "Tagged Image File Format";
break;
case "PNG":
caption = "Portable Network Graphics";
break;
default:
caption = encoder.FormatDescription;
break;
}
sb.AppendFormat("|{0} ({1})|{2}", caption, ext.Replace(";", ", "), ext);
}
return sb.ToString();
}
Use it like this:
var dlg = new OpenFileDialog {
Filter = SupportedImageDecodersFilter(),
Multiselect = false,
Title = "Choose Image"
};
The code above (slightly modified) can be used to find available image file extensions. In order to test if a given file extension denotes an image, I would put the valid extension in a HashSet
. HashSets have an
O(1) access time! Make sure to choose a case insensitive string comparer. Since the file extensions do not contain accented or non Latin letters, the culture can safely be ignored. Therefore I use an ordinal string comparison.
var imageExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
imageExtensions.Add(".png");
imageExtensions.Add(".bmp");
...
And test if a filename is an image:
string extension = Path.GetExtension(filename);
bool isImage = imageExtensions.Contains(extension);