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.
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]
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?