Using WPF Imaging classes - Getting image dimensio

2020-05-15 00:25发布

问题:

Link this post I want to be able to read an image files height and width without reading in the whole file into memory.

In the post Frank Krueger mentions there is a way of doing this with some WPF Imaging classes. Any idea on how to do this??

回答1:

This should do it:

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;


回答2:

Following Sir Juice's recommendation, here is some alternative code that avoids locking the image file:

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;
}