Is there quick way to get the ImageFormat object associated to a particular file extension? I'm looking for quicker than string comparisons for each format.
Asked
Active
Viewed 3.3k times
4 Answers
35
Here's some old code I found that should do the trick:
var inputSource = "mypic.png";
var imgInput = System.Drawing.Image.FromFile(inputSource);
var thisFormat = imgInput.RawFormat;
This requires actually opening and testing the image--the file extension is ignored. Assuming you are opening the file anyway, this is much more robust than trusting a file extension.
If you aren't opening the files, there's nothing "quicker" (in a performance sense) than a string comparison--certainly not calling into the OS to get file extension mappings.

richardtallent
- 34,724
- 14
- 83
- 123
-
5Why do you need the line `Graphics gInput = Graphics.FromImage(imgInput);`? `gInput` is not used at all. – Tim Schmelter Sep 25 '14 at 08:15
-
Maybe, he wanted to put all this in a Try-Catch and see if it works. – RealityDysfunction Oct 08 '14 at 15:58
-
This is rather useless for a "save as..." scenario, though. – Nyerguds Feb 26 '15 at 09:55
-
@TimSchmelter, good point, I've removed the extra call. It was there because this came from production code where I was using the image after detecting the type. – richardtallent Jun 07 '20 at 22:49
35
private static ImageFormat GetImageFormat(string fileName)
{
string extension = Path.GetExtension(fileName);
if (string.IsNullOrEmpty(extension))
throw new ArgumentException(
string.Format("Unable to determine file extension for fileName: {0}", fileName));
switch (extension.ToLower())
{
case @".bmp":
return ImageFormat.Bmp;
case @".gif":
return ImageFormat.Gif;
case @".ico":
return ImageFormat.Icon;
case @".jpg":
case @".jpeg":
return ImageFormat.Jpeg;
case @".png":
return ImageFormat.Png;
case @".tif":
case @".tiff":
return ImageFormat.Tiff;
case @".wmf":
return ImageFormat.Wmf;
default:
throw new NotImplementedException();
}
}

Ryan Williams
- 1,465
- 15
- 19
-
This is the better option if opening the file isn't possible. For example, loading a very large image may cause an `OutOfMemory` exception. This isn't as robust, will do for many use-cases. – TEK May 09 '16 at 15:56
4
private static ImageFormat GetImageFormat(string format)
{
ImageFormat imageFormat = null;
try
{
var imageFormatConverter = new ImageFormatConverter();
imageFormat = (ImageFormat)imageFormatConverter.ConvertFromString(format);
}
catch (Exception)
{
throw;
}
return imageFormat;
}

Barda
- 49
- 1
- 1
-
1I don't understand why this is upvoted! imageFormatConverter.ConvertFromString is inherited from TypeConverter and always returns null or throws a NotSupportedException! [see this](https://stackoverflow.com/a/3594313/2803565) – S.Serpooshan Dec 10 '17 at 11:45
1
see the CodeProject article on File Associations http://www.codeproject.com/KB/dotnet/System_File_Association.aspx

Robert French
- 686
- 4
- 12