Monday, July 19, 2010

OpenFileDialog image filter string

I wanted to open a dialog in .NET asking for an image file and so I needed to construct a filter with all supported image types. Strangely enough, I didn't find it on Google, so I did it myself. Here is a piece of code that gets the filter string for you:

private string getImageFilter()
StringBuilder sb=new StringBuilder();
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo info in codecs)
if (sb.Length > 0)
return sb.ToString();
As you can see, it enumerated through the image encoders list and creates the extension list. The filter, then, is obtained as

filter = string.Format(
"Image Files({0})|{0}|All files (*.*)|*.*",

Before using it, though, here is the (surprisingly disappointing) filter string: *.BMP;*.DIB;*.RLE;*.JPG;*.JPEG;*.JPE;*.JFIF;*.GIF;*.TIF;*.TIFF;*.PNG
Kind of short, isn't it?


ctrlbr34k said...

Thanks. Not only it works, but it's a very clever solution. Thanks again.