Jam*_*s R 5 .net c# wpf bitmapimage
如何获取 System.Windows.Media.Imaging.BitmapImage 支持的图像格式列表?
我正在用 C# WPF 编写一个简单的图像处理工具。BitmapImage 类是更有用的位图类之一,因为它能够从多种格式进行解码。
特别是,它可以在我的电脑上打开 NEF(尼康的 RAW 格式)。BitmapImage 很可能可以打开来自其他制造商的各种 RAW 格式,这是我热衷于使用的功能。
由于我不知道可以作为 BitmapImage 打开的每种格式,我目前正在使用 try/catch 尝试从用户尝试打开的每个文件构建 BitmapImage。这显然不是最有效的方式。
据我所知,BitmapImage 继承自 BitmapSource,BitmapSource通过查看用户系统的可用编解码器来决定它可以打开哪些文件。因此,编解码器的可用性可能因机器而异,这意味着无法将支持的格式列表硬编码到程序中。我需要一种方法来检查用户机器上支持的这些格式是什么。
我在 System.Drawing 中找到了这个方法。这将返回支持的编解码器列表以及支持的文件扩展名列表,Systems.Windows.Media.Imaging 的等效项正是我所需要的。
如果您不想直接处理 WIC,如Clemens 提到的答案中链接的源代码所示,您可以阅读附加编解码器列表(默认情况下 WIC 不支持的编解码器)及其名称和支持的文件直接从注册表扩展。
请参阅以下示例代码。
/// <summary>
/// Sample code: Show the additional registered decoders
/// </summary>
private void Button_Click(object sender, RoutedEventArgs e)
{
var additionalDecoders = GetAdditionalDecoders();
foreach(var additionalDecoder in additionalDecoders)
{
MessageBox.Show(additionalDecoder.FriendlyName + ":" + additionalDecoder.FileExtensions);
}
}
/// <summary>
/// GUID of the component registration group for WIC decoders
/// </summary>
private const string WICDecoderCategory = "{7ED96837-96F0-4812-B211-F13C24117ED3}";
/// <summary>
/// Represents information about a WIC decoder
/// </summary>
public struct DecoderInfo
{
public string FriendlyName;
public string FileExtensions;
}
/// <summary>
/// Gets a list of additionally registered WIC decoders
/// </summary>
/// <returns></returns>
public static IEnumerable<DecoderInfo> GetAdditionalDecoders()
{
var result = new List<DecoderInfo>();
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;
}
Run Code Online (Sandbox Code Playgroud)
请注意,这可能会返回不同的结果,具体取决于您是在 32 位还是 64 位进程中运行。例如,在我的 Windows 10 机器上,我安装了 Microsoft 的 Photoshop 解码器来读取 psd 文件。但是,仅安装了 32 位版本。
因此,当我尝试通过 加载 Photoshop psd 文件时BitmapImage,这在运行 32 位应用程序时会成功,但在运行 64 位应用程序时不会。上面从注册表中读取已安装解码器的代码正确反映了这一点。