Get ImageFormat from File Extension

后端 未结 4 1979
萌比男神i
萌比男神i 2020-12-25 11:45

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.

相关标签:
4条回答
  • 2020-12-25 12:08
    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();
        }
    }
    
    0 讨论(0)
  • 2020-12-25 12:16

    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.

    0 讨论(0)
  • 2020-12-25 12:20

    see the CodeProject article on File Associations http://www.codeproject.com/KB/dotnet/System_File_Association.aspx

    0 讨论(0)
  • 2020-12-25 12:25
        private static ImageFormat GetImageFormat(string format)
        {
            ImageFormat imageFormat = null;
    
            try
            {
                var imageFormatConverter = new ImageFormatConverter();
                imageFormat = (ImageFormat)imageFormatConverter.ConvertFromString(format);
            }
            catch (Exception)
            {
    
                throw;
            }
    
            return imageFormat;
        }
    
    0 讨论(0)
提交回复
热议问题