使用WPF Imaging类 - 获取图像尺寸而不读取整个文件

vdh*_*ant 20 wpf file-io metadata image image-processing

链接这篇文章我希望能够读取图像文件的高度和宽度,而无需将整个文件读入内存.

在Frank Krueger的帖子中提到,有一种方法可以通过一些WPF Imaging类来实现.关于如何做到这一点的任何想法?

Ken*_*art 45

这应该这样做:

var bitmapFrame = BitmapFrame.Create(new Uri(@"C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg"), BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
var width = bitmapFrame.PixelWidth;
var height = bitmapFrame.PixelHeight;
Run Code Online (Sandbox Code Playgroud)

  • 请注意,此方法将在图像文件上放置_lock_.要避免这种情况,请在using块(使用FileMode.Read,FileAccess.Read)中创建FileStream,然后使用流而不是嵌入的URI创建BitmapFrame.肯特本人在这里使用这种技术:http://stackoverflow.com/questions/767250/using-bitmapframe-for-metadata-without-locking-the-file (2认同)

Cha*_*lie 19

按照Juice爵士的建议,这里有一些替代代码可以避免锁定图像文件:

using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
    var bitmapFrame = BitmapFrame.Create(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
    var width = bitmapFrame.PixelWidth;
    var height = bitmapFrame.PixelHeight;
}
Run Code Online (Sandbox Code Playgroud)

  • 此外,使用 [SysInternals ProcessMonitor](https://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) 我只观察到 4 个 `ReadFile` 事件,位于 `(offset,length) = (0,16), (0,14), (14,4), (18,36)` 总共从文件中读取了 70 个字节。极好的! (2认同)