确定WPF是否可以加载图像文件的最佳方法是什么?

确定WPF是否可以加载图像文件的最佳方法是什么?

问题描述:

有什么方法可以确定WPF是否能够加载图像文件而无需尝试构造BitmapImage并在失败时捕获异常吗?

Is there any way to determine if WPF will be able to load an image file without attempting to construct a BitmapImage and catching the exception if it fails?

我正在创建一个图像浏览器,试图在可移动驱动器上显示所有图像的预览.可能有很多不是图像的文件,每个文件捕获一个异常似乎效率不高,但我想不出一种不容易出错的方法.

I'm creating an image browser that attempts to show previews of all the images on a removable drive. There could be a lot of files that aren't images and catching an exception for each one seems somewhat inefficient but I can't think of a way that isn't prone to error.

有什么建议吗?

谢谢,标记

我最近问了一个非常类似的问题,并在这里得到了一个很好的答案..

I recently asked a very similar question and got an excellent answer here.

基本上,可以在用户计算机上找到所有的编解码器,BitmapImage可以使用这些编解码器打开各种图像格式.通过这些编解码器,您可以构建这些文件可以打开的文件扩展名的列表.

Basically, you find all the codecs on a user's machine which BitmapImage can use to open various image formats. From these codecs, you build a list of the file extensions that these can open.

然后,当您的程序尝试打开文件时,请对照此列表检查该文件的扩展名.

Then, when your program tries to open a file, check the extension of that file against this list.

WPF使用WIC处理图像.它包含一组处理常见图像格式的编解码器核心,我相信您可以从以上答案中的代码在您的计算机上搜索这些额外的编解码器,并提供了相应的文件扩展名.

WPF uses WIC to handle images. It contains a core set of codecs that handle common image formats, and I believe you can hard-code the extensions of these from here. WIC is also extensible, so, for example, camera manufacturers can incorporate custom image formats into WIC. The code in the answer above searches your computer for these extra codecs, and provides the corresponding file extensions for these.

此方法假定文件扩展名对于文件是正确的.不过,在大多数情况下,这通常是一个合理的假设-即使Windows资源管理器也乐于接受这一假设.尽管如此,如果奇数流氓文件出现在扩展名是图像的位置,但仍然无法打开,我将把BitmapImage结构包装在try-catch中.

This method assumes that the file extensions are correct for a file. This is usually a fair assumption in most cases though - even Windows Explorer is happy to assume this. Still, I would wrap the BitmapImage construction in a try-catch, should the odd rogue file appear where the extension appears to be an image, but it still won't open.

我也将此功能包装到一个类中,您可以将其复制粘贴到您自己的项目中此处.

I have also wrapped this functionality into a class you can copy-paste into your own project here.