20

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??

Community
  • 1
  • 1
vdh_ant
  • 12,720
  • 13
  • 66
  • 86

2 Answers2

46

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;
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • 2
    Note that this method will place a _lock_ on the image file. To avoid this, create a FileStream in a using block (with FileMode.Read, FileAccess.Read), and then create the BitmapFrame using the stream rather than the embedded URI. Kent himself uses this technique here: http://stackoverflow.com/questions/767250/using-bitmapframe-for-metadata-without-locking-the-file – Charlie Dec 11 '13 at 19:46
  • @Charlie Why not put down the code as an alternative answer and earn some rep? –  Aug 05 '14 at 07:36
23

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;
}
Charlie
  • 15,069
  • 3
  • 64
  • 70
  • I did a cursory check for memory allocation by wrapping this code with `GC.GetTotalMemory(false)`. I checked a 4k bitmap image (4096x2160, ~34MB on disk) and the amount of memory allocated was around 16kB. – cod3monk3y Jan 23 '15 at 00:09
  • 2
    Additionally, using [SysInternals ProcessMonitor](https://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) I observed only 4 `ReadFile` events at `(offset,length) = (0,16), (0,14), (14,4), (18,36)` for a grand total of 70 bytes read from the file. Fantastic! – cod3monk3y Jan 23 '15 at 00:14
  • @cod3monk3y referencing ProcMon – JJS Jun 13 '16 at 13:37
  • @Charlie : Is there any way to get image file size as well without loading the complete image in memory. – Koder101 Jan 09 '17 at 08:12