Good way to check if file extension is of an image or not
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);
An option would be to have a list of all possible valid image extensions, then that method would only check if the supplied extension is within that collection:
private static readonly HashSet<string> validExtensions = new HashSet<string>()
{
"png",
"jpg",
"bmp"
// Other possible extensions
};
Then in the validation you just check against that:
public static bool IsImageExtension(string ext)
{
return validExtensions.Contains(ext);
}
You could use .endsWith(ext)
. It's not a very secure method though: I could rename 'bla.jpg' to 'bla.png' and it would still be a jpg file.
public static bool HasImageExtension(this string source){
return (source.EndsWith(".png") || source.EndsWith(".jpg"));
}
This provides a more secure solution:
string InputSource = "mypic.png";
System.Drawing.Image imgInput = System.Drawing.Image.FromFile(InputSource);
Graphics gInput = Graphics.fromimage(imgInput);
Imaging.ImageFormat thisFormat = imgInput.rawformat;
private static readonly string[] _validExtensions = {"jpg","bmp","gif","png"}; // etc
public static bool IsImageExtension(string ext)
{
return _validExtensions.Contains(ext.ToLower());
}
If you want to be able to make the list configurable at runtime without recompiling, add something like:
private static string[] _validExtensions;
private static string[] ValidExtensions()
{
if(_validExtensions==null)
{
// load from app.config, text file, DB, wherever
}
return _validExtensions
}
public static bool IsImageExtension(string ext)
{
return ValidExtensions().Contains(ext.ToLower());
}