| Reading Photo Metadata Using Windows Imaging Component by Ben Vincent |
I still see a lot of questions on the Internet and at work on how to read (& write) metadata in Photos. There are plenty of examples out there but they all appear to have some pitfalls. To be quite honest, the code I’ve been using for a number of years now is mature enough that it solves almost all the problems I’ve seen. This blog is the first in a series that document how to read (this blog), write and manipulate photo metadata. You can find all my blogs on Windows Imaging Component here. All this code is based on Windows Presentation Foundation (so you’ll need a reference to PresentationCore) which includes the Windows Imaging Component. These classes provide some very solid tools for reading and manipulating images. In particular the BitmapMetadata object provides access to data stored in Exif, XMP or IPTC in a file. The following method takes a jpg photo filename as the parameter and returns a BitmapMetadata object. | public static BitmapMetadata ReadMetadata(string sourceFile) { BitmapMetadata sourceMetadata = null; BitmapCreateOptions createOptions = BitmapCreateOptions.PreservePixelFormat | BitmapCreateOptions.IgnoreColorProfile; // Open the File using (Stream sourceStream = File.Open(sourceFile, FileMode.Open, FileAccess.Read)) { // Decode the file and cache the content onload (BitmapCacheOption.OnLoad) // If you don't do this sourceMetadata won't be fully loaded BitmapDecoder sourceDecoder = BitmapDecoder.Create(sourceStream, createOptions, BitmapCacheOption.OnLoad); // Check source has valid frames if (sourceDecoder.Frames[0] != null && sourceDecoder.Frames[0].Metadata != null) { // Clone the metadata so we can throw away the reference to the underlying file sourceMetadata = sourceDecoder.Frames[0].Metadata.Clone() as BitmapMetadata; } else { throw new Exception("Unable to read Metadata from File"); } } return sourceMetadata; } | It’s a static method so you get an in-memory copy of all the metadata. If you plan to change the return type to a specific property, then you can change BitmapCacheOption to None. This is faster, because the everything is loaded on the demand but it means BitmapMetadata is only valid whilst the sourceStream is in scope. In my next blog I’ll talk about how to save changes made to the BitmapMetadata object we’ve retrieved. |
|
|
| Posted: Tue, 3 Nov 2009, 07:37:33 GMT (Updated: Wed, 4 Nov 2009, 05:42:15 GMT) by Ben Vincent | 0 Comments |
| Category: Development |
| Tags: Windows Imaging Component, XMP, Exif, IPTC, FotoFly |
|
| |