Alex
Alex

Reputation: 743

Powershell read metadata of large files

I've got a script that loops through a load of images that I've taken and reads the Focal Length & Camera Model, presenting a graph of focal lengths and totals (which is great for helping determine the next lens purchase, but that's besides the point).

This works absolutely fine for JPG images under 10 MB but as soon as it hits a RAW file (like Canon's CR2 format) nearer 20 MB, it spits out "Out of Memory" errors.

Is there a way to either increase the memory limit in Powershell, or just read a file's metadata without loading the entire file..?

This is what I'm currently using:

# load image by statically calling a method from .NET
$image = [System.Drawing.Imaging.Metafile]::FromFile($file.FullName)

# try to get the ExIf data (silently fail if the data can't be found)
# http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/EXIF.html
try
{
  # get the Focal Length from the Metadata code 37386
  $focalLength = $image.GetPropertyItem(37386).Value[0]
  # get model data from the Metadata code 272
  $modelByte = $image.GetPropertyItem(272)
  # convert the model data to a String from a Byte Array
  $imageModel = $Encode.GetString($modelByte.Value)
  # unload image
  $image.Dispose()
}
catch
{
  #do nothing with the catch
}

I have tried using the solution here: http://goo.gl/WY7Rg but CR2 files just return blanks on any property...

Any help greatly appreciated!

Upvotes: 0

Views: 2448

Answers (2)

abrodersen
abrodersen

Reputation: 153

The problem is that the image object is not getting disposed when an error occurs. Execution exits the try block when an error occurs, meaning the Dispose call never executes and the memory is never returned.

To fix this, you must to put the $image.Dispose() call inside a finally block at the end of your try/catch. Like this

try
{
  /* ... */
}
catch
{
  #do nothing with the catch
}
finally
{
  # ensure image is always unloaded by placing this code in a finally block
  $image.Dispose()
}

Upvotes: 5

CB.
CB.

Reputation: 60938

I use this module for get EXIF data on image. I had never test it on .CR2 but on .CRW of about 15MB.

Try it and let me know.

Upvotes: 0

Related Questions