从BitmapImage获取支持的图像格式

如何获取System.Windows.Media.Imaging.BitmapImage支持的图像格式列表?

我正在用C#WPF编写一个简单的图像处理工具。 BitmapImage类是更有用的位图类之一,因为它能够从各种格式进行解码。

特别是,它能够在我的电脑上打开NEF(尼康的RAW格式)。 BitmapImage可能会打开来自其他制造商的各种RAW格式,这是我热衷于使用的function。

由于我不知道每个可以作为BitmapImage打开的格式,我目前正在使用try / catch尝试从用户尝试打开的每个文件构造一个BitmapImage。 这显然不是最有效的方式。

据我所知,BitmapImageinheritance自BitmapSource,它通过在用户的系统上查找可用的编解码器来决定它可以打开哪些文件 。 因此,编解码器可用性可能因机器而异,这意味着支持的格式列表无法硬编码到程序中。 我需要一种方法来检查用户机器上支持的格式是什么。

我在System.Drawing中找到了这个方法 。 这将返回支持的编解码器列表,其中包含受支持的文件扩展名列表,而Systems.Windows.Media.Imaging的等效编辑器正是我所需要的。

如果您不想直接处理WIC,如Clemens提到的答案中链接的源代码所示,您可以读取其他编解码器列表(默认情况下WIC不支持的编解码器)及其名称和支持的文件直接来自注册表的扩展。

请参阅以下示例代码。

///  /// Sample code: Show the additional registered decoders ///  private void Button_Click(object sender, RoutedEventArgs e) { var additionalDecoders = GetAdditionalDecoders(); foreach(var additionalDecoder in additionalDecoders) { MessageBox.Show(additionalDecoder.FriendlyName + ":" + additionalDecoder.FileExtensions); } } ///  /// GUID of the component registration group for WIC decoders ///  private const string WICDecoderCategory = "{7ED96837-96F0-4812-B211-F13C24117ED3}"; ///  /// Represents information about a WIC decoder ///  public struct DecoderInfo { public string FriendlyName; public string FileExtensions; } ///  /// Gets a list of additionally registered WIC decoders ///  ///  public static IEnumerable GetAdditionalDecoders() { var result = new List(); string baseKeyPath; // If we are a 32 bit process running on a 64 bit operating system, // we find our config in Wow6432Node subkey if (Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess) { baseKeyPath = "Wow6432Node\\CLSID"; } else { baseKeyPath = "CLSID"; } RegistryKey baseKey = Registry.ClassesRoot.OpenSubKey(baseKeyPath, false); if (baseKey != null) { var categoryKey = baseKey.OpenSubKey(WICDecoderCategory + "\\instance", false); if (categoryKey != null) { // Read the guids of the registered decoders var codecGuids = categoryKey.GetSubKeyNames(); foreach (var codecGuid in codecGuids) { // Read the properties of the single registered decoder var codecKey = baseKey.OpenSubKey(codecGuid); if (codecKey != null) { DecoderInfo decoderInfo = new DecoderInfo(); decoderInfo.FriendlyName = Convert.ToString(codecKey.GetValue("FriendlyName", "")); decoderInfo.FileExtensions = Convert.ToString(codecKey.GetValue("FileExtensions", "")); result.Add(decoderInfo); } } } } return result; } 

请注意,这可能会返回不同的结果,具体取决于您是在32位还是64位进程中运行。 例如,在我的Windows 10机器上,我安装了Microsoft的Photoshop解码器来读取psd文件。 但是,只安装了32位版本。

因此,当我尝试通过BitmapImage加载Photoshop psd文件时,这在运行32位应用程序时成功,但在运行64位应用程序时则不成功。 从注册表中读取已安装的解码器的上述代码正确地反映了这一点。