get extension from System.Drawing.Imaging.ImageFormat (C#)

15,624

Solution 1

mayby this is what you are looking for?

    public static string GetFilenameExtension(ImageFormat format)
    {
        return ImageCodecInfo.GetImageEncoders().FirstOrDefault(x => x.FormatID == format.Guid).FilenameExtension;
    }

Solution 2

I have now found 3 ways to do this, of which, the last 2 are equivalent. All are extension methods and intend to produce an extension in the form ".foo"

static class ImageFormatUtils
{
    //Attempt 1: Use ImageCodecInfo.GetImageEncoders
    public static string FileExtensionFromEncoder(this ImageFormat format)
    {
        try
        {
            return ImageCodecInfo.GetImageEncoders()
                    .First(x => x.FormatID == format.Guid)
                    .FilenameExtension
                    .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                    .First()
                    .Trim('*')
                    .ToLower();
        }
        catch (Exception)
        {
            return ".IDFK";
        }
    }

    //Attempt 2: Using ImageFormatConverter().ConvertToString()
    public static string FileExtensionFromConverter(this ImageFormat format)
    {
        return "." + new ImageFormatConverter().ConvertToString(format).ToLower();
    }

    //Attempt 3: Using ImageFormat.ToString()
    public static string FileExtensionFromToString(this ImageFormat format)
    {
        return "." + format.ToString().ToLower();
    }
}

Being extension methods they can be called like:

ImageFormat format = ImageFormat.Jpeg;
var filePath = "image" + format.FileExtensionFromEncoder();

The resulting string will be:

"image.jpg"

To compare these new methods I made a short console app:

class Program
{
    static void Main()
    {
        var formats = new[]
        {
            ImageFormat.Bmp, ImageFormat.Emf, ImageFormat.Exif, ImageFormat.Gif,
            ImageFormat.Icon, ImageFormat.Jpeg, ImageFormat.MemoryBmp, ImageFormat.Png,
            ImageFormat.Tiff, ImageFormat.Wmf
        };

        foreach (var format in formats)
        {
            Console.WriteLine("FromEncoder: '{0}', FromConverter: '{1}', FromToString: '{2}'", format.FileExtensionFromEncoder(), format.FileExtensionFromConverter(), format.FileExtensionFromToString());
        }
        Console.Read();
    }
}

Running this results in the following output:

FromEncoder: '.bmp', FromConverter: '.bmp', FromToString: '.bmp'
FromEncoder: '.IDFK', FromConverter: '.emf', FromToString: '.emf'
FromEncoder: '.IDFK', FromConverter: '.exif', FromToString: '.exif'
FromEncoder: '.gif', FromConverter: '.gif', FromToString: '.gif'
FromEncoder: '.IDFK', FromConverter: '.icon', FromToString: '.icon'
FromEncoder: '.jpg', FromConverter: '.jpeg', FromToString: '.jpeg'
FromEncoder: '.IDFK', FromConverter: '.memorybmp', FromToString: '.memorybmp'
FromEncoder: '.png', FromConverter: '.png', FromToString: '.png'
FromEncoder: '.tif', FromConverter: '.tiff', FromToString: '.tiff'
FromEncoder: '.IDFK', FromConverter: '.wmf', FromToString: '.wmf'

You can see that the original method fails and produces a '.IDFK' on the more obscure formats while the other methods are actually just using the name of the format; ImageFormat.Jpeg, '.jpeg'; ImageFormat.MemoryBmp, '.memorybmp'; etc..

So as the original question wants '.tif' rather then '.tiff', it would seem the first method is for you. Or maybe some combination of the 2 would be ideal:

    public static string FileExtensionFromEncoder(this ImageFormat format)
    {
        try
        {
            return ImageCodecInfo.GetImageEncoders()
                    .First(x => x.FormatID == format.Guid)
                    .FilenameExtension
                    .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                    .First()
                    .Trim('*')
                    .ToLower();
        }
        catch (Exception)
        {
            return "." + format.ToString().ToLower();
        }
    }

Solution 3

Kevin Bray's answer is great. I wasn't 100% happy with relying on catching an exception in this way though, so I tweaked his solution very slightly...

public static string GetFileExtension(this ImageFormat imageFormat)
{
    var extension = ImageCodecInfo.GetImageEncoders()
        .Where(ie => ie.FormatID == imageFormat.Guid)
        .Select(ie => ie.FilenameExtension
            .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
            .First()
            .Trim('*')
            .ToLower())
        .FirstOrDefault();

    return extension ?? string.Format(".{0}", imageFormat.ToString().ToLower());
}

Solution 4

In my production code I use this:

    public static string GetExtensionFromImageFormat(ImageFormat img)
    {
        if (img.Equals(ImageFormat.Jpeg)) return ".jpg";
        else if (img.Equals(ImageFormat.Png)) return ".png";
        else if (img.Equals(ImageFormat.Gif)) return ".gif";
        else if (img.Equals(ImageFormat.Bmp)) return ".bmp";
        else if (img.Equals(ImageFormat.Tiff)) return ".tif";
        else if (img.Equals(ImageFormat.Icon)) return ".ico";
        else if (img.Equals(ImageFormat.Emf)) return ".emf";
        else if (img.Equals(ImageFormat.Wmf)) return ".wmf";
        else if (img.Equals(ImageFormat.Exif)) return ".exif";
        else if (img.Equals(ImageFormat.MemoryBmp)) return ".bmp";
        return ".unknown";
    }

Solution 5

I did some refining on Niklas answer because I was looking for a way of getting a file extension suitable to be appended to a file name. I'm posting my solution here just in case other googlers out there are looking for the same thing:

public string GetFilenameExtension(ImageFormat format)
{
    return ImageCodecInfo.GetImageEncoders()
                         .First(x => x.FormatID == format.Guid)
                         .FilenameExtension
                         .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
                         .First()
                         .Trim('*');
}

So if you call it like this:

var filePath = "image" + GetFilenameExtension(ImageFormat.Jpeg);

The resulting string will be:

"image.JPG"
Share:
15,624

Related videos on Youtube

Karl Cassar
Author by

Karl Cassar

A passionate coder & web developer based in Malta (Europe) who constantly tries to keep abreast of the latest technologies and finding new ways to increase code quality and robustness. Focusing mainly on .Net technologies / C#. Lately became extremely keen on TDD, BDD and similar practices/methodologies to constantly improve on software quality, reliability and coding efficiency.

Updated on September 15, 2022

Comments

  • Karl Cassar
    Karl Cassar over 1 year

    Is it possible to get the extension, for any given System.Drawing.Imaging.ImageFormat? (C#)

    Example:

    System.Drawing.Imaging.ImageFormat.Tiff -> .tif
    System.Drawing.Imaging.ImageFormat.Jpeg -> .jpg
    ...
    

    This can easily be done as a lookup table, but wanted to know if there is anything natively in .Net.

  • niklascp
    niklascp over 11 years
    (surely you should test if FirstOrDefault actually finds something before calling its property ;)
  • user1703401
    user1703401 over 11 years
    Quote: The extensions are separated by semicolons
  • dafie
    dafie about 5 years
    For System.Drawing.Imaging.ImageFormat.Png it returns *.PNG instead .png, as op requested.