【问题标题】:Get ImageFormat from File Extension从文件扩展名获取 ImageFormat
【发布时间】:2010-11-23 04:35:33
【问题描述】:

有没有快速的方法来获取关联到特定文件扩展名的 ImageFormat 对象?我正在寻找比每种格式的字符串比较更快的方法。

【问题讨论】:

    标签: c# .net image


    【解决方案1】:

    这是我发现的一些旧代码,应该可以解决问题:

     var inputSource = "mypic.png";
     var imgInput = System.Drawing.Image.FromFile(inputSource);
     var thisFormat = imgInput.RawFormat;
    

    这需要实际打开和测试图像——文件扩展名被忽略。假设您仍然要打开文件,这比信任文件扩展名要可靠得多。

    如果您不打开文件,没有什么比字符串比较“更快”(在性能方面)了——当然不会调用操作系统来获取文件扩展名映射。

    【讨论】:

    • 为什么需要Graphics gInput = Graphics.FromImage(imgInput);这一行? gInput 根本没有使用。
    • 也许,他想把所有这些都放在一个 Try-Catch 中,看看它是否有效。
    • 不过,这对于“另存为...”场景来说是相当无用的。
    • @TimSchmelter,好点,我已经删除了额外的电话。它在那里是因为它来自生产代码,我在检测到类型后使用图像。
    【解决方案2】:
    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();
        }
    }
    

    【讨论】:

    • 如果无法打开文件,这是更好的选择。例如,加载非常大的图像可能会导致OutOfMemory 异常。这不是那么健壮,适用于许多用例。
    【解决方案3】:
        private static ImageFormat GetImageFormat(string format)
        {
            ImageFormat imageFormat = null;
    
            try
            {
                var imageFormatConverter = new ImageFormatConverter();
                imageFormat = (ImageFormat)imageFormatConverter.ConvertFromString(format);
            }
            catch (Exception)
            {
    
                throw;
            }
    
            return imageFormat;
        }
    

    【讨论】:

    • 我不明白为什么这是赞成的! imageFormatConverter.ConvertFromString 继承自 TypeConverter,总是返回 null 或者抛出 NotSupportedException! see this
    【解决方案4】:

    请参阅 CodeProject 关于文件关联的文章 http://www.codeproject.com/KB/dotnet/System_File_Association.aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 1970-01-01
      • 2011-05-16
      • 1970-01-01
      • 2012-06-07
      • 2016-09-01
      相关资源
      最近更新 更多