Click here to Skip to main content
11,484,162 members (67,313 online)
Click here to Skip to main content

ExifLib - A Fast Exif Data Extractor for .NET 2.0+

, 22 Sep 2014 CPOL 299.3K 12.2K 282
Rate this:
Please Sign up or sign in to vote.
Reads JPEG Exif data without the heavyweight and unnecessary instantiation of GDI+ objects.

Exif Lib - test application

Introduction

ExifLib simply reads Exif tags (i.e., camera model, GPS data, date picture taken, shutter speed etc.) from JPEG files, without the overhead introduced by using the GDI+ classes located in System.Drawing.Imaging, and with less lines of code for the developer.

Background

I've been using a simple command line application to move my photos into subdirectories based on the date on which they were created. As with all other .NET Exif implementations I've seen, I was using the PropertyItem class located in System.Drawing.Imaging. While this does the job, I often found myself processing thousands of images at a time, and the .NET classes were just too slow for the job. ExifLib goes back to the JPEG/TIFF standard itself, and only reads the essentials, using little more than the file input classes in System.IO.

Using the Code

ExifLib is very simple, with only one class and one enum in the namespace. Just add a reference to ExifLib.dll, and you're good to go! An example follows:

using ExifLib;
...
...
...
// Instantiate the reader
using (ExifReader reader = new ExifReader(@"C:\temp\testImage.jpg"))
{
    // Extract the tag data using the ExifTags enumeration
    DateTime datePictureTaken;
    if (reader.GetTagValue<DateTime>(ExifTags.DateTimeDigitized, 
                                    out datePictureTaken))
    {
        // Do whatever is required with the extracted information
        MessageBox.Show(this, string.Format("The picture was taken on {0}", 
           datePictureTaken), "Image information", MessageBoxButtons.OK);
    }
}

Note that the ExifReader class holds the image file open, so once you're finished with the reader, be sure to call its Dispose method, either explicitly, or implicitly through a using statement (as in the above example).

How it works

Exif data is stored in the JPEG header, inside the APP1 block. This block contains a number of IFDs (image file directories). These include the EXIF IFD and the GPS IFD, which contain the tags available for retrieval by this library.

The IFDs start with a catalogue of EXIF tags and the stream offsets to where the data for each tag is stored. On instantiation, the library creates a Dictionary of these tag offsets, which are accessed during retrieval of a specific tag's value. It's this lazy retrieval which gives the library its speed, as most EXIF use-cases only involve retrieving a handful of tag values, so there's little use in retrieving tag values before they're required.

Points of Interest

Something strange that I learned while writing this library is that while JPEG stipulates "Big Endian" encoding (i.e., numbers read from left to right), the TIFF standard allows Big or Little Endian encoding. Since the Exif tags are encoded using TIFF encoding, often the JPEG will be read using "Big Endian" encoding until the TIFF section is reached, at which point the encoding reverses and the rest of the document is read using "Little Endian" encoding.

During coding, I realised from a comment on the ExifWorks CodeProject article that it's possible to increase performance when using System.Drawing.Image by setting the constructor's validateImageData parameter to false. However, even when using this enhancement, ExifLib still performs 50% faster, possibly because it does not read the tag values until they're requested. I have also noticed that ExifLib performs similarly with small (<1MP) images, but scales better when loading larger images. The screenshot at the top of this page was produced using a 12MP image.

History

Version 1.1

  • Array extraction has been added, thanks to a comment from Justin Carasick. This is used in various fields, including GPS coordinates and Exif versioning. The previous version of ExifLib would only return the first element from an array.

Version 1.2

  • Fixed bug when retrieving data for fields shorter than 4 bytes, thanks to a comment from bartsy. The previous version of ExifLib would lose important data from these fields when processing big-endian encoded files.
  • Updated the project to Visual Studio 2010, refactored a little of the code. The project is still .NET 2.0+.

Version 1.3

  • Added the ability to extract JPEG encoded thumbnails from images, thanks to a comment from StyrianOak. Note that uncompressed (i.e. TIFF) encoded thumbnails are not supported, but since any camera which supports the DCF standard will produce JPEG thumbnails, this is a minor limitation.

Version 1.4

  • Added a constructor overload to allow reading of JPEG data from any seekable stream
  • Modified code to allow compiling for Windows Phone and Silverlight. The NuGet package now includes Windows Phone and Silverlight DLLs.
  • Improved support for null DateTime values thanks to comments from schurig and BrandonOrding
  • undefined Exif fields are now returned as byte[] instead of uint[]
  • Fixed a bug in the thumbnail extractor where thumbnails with 0xFF padding were not being recognised, thanks to a comment from _d-fens_.
  • Added the option to retrieve a TIFF rational as an int[] {numerator, denominator} array (instead of double), thanks to a comment from Member 10226163.
  • Changed thumbnail padding detection code to accept 0x00 as well as 0xFF as padding bytes, thanks to a comment from Cruiser77
  • Added conditional compilation options for Windows Store app compatibility, thanks to a comment from _dieQueeQ.

Version 1.5

  • Fixed an exception when reading images containing tags without datatypes
  • Refactored to store tag data in separate dictionaries for each IFD
  • Added the ability to extract metadata from images which don't contain the EXIF sub IFD, thanks to a Charlie Hess

Version 1.6

  • On frameworks prior to 4.5, an exception thrown while initialising the reader can result in the stream being closed. Added code for 4.5+ to prevent this from happening
  • Added a new constructor parameter for framework 4.5+ to allow the user to indicate that the supplied stream should be left open when the reader is disposed
  • Thanks to a comment from disore, fixed ArgumentExceptions thrown when the end of the stream is reached during instantiation; wrapped some instantiation exceptions in ExifLibExceptions.

NuGet Release

ExifLib is now available on nuget! Simply install from the Visual Studio Package Manager Console using Install-Package ExifLib.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Simon McKenzie
Software Developer BreastScreen Victoria
Australia Australia

Simon McKenzie has been working as a developer for 10 years, primarily in .NET, with interests in imaging and GIS, particularly on mobile platforms. He is the author of the award winning MapSnap GPS, a moving map application for Windows Phone. He's also the author of the popular (free) high-speed ExifLib EXIF extractor for .NET.


Comments and Discussions

 
GeneralLearn from you Pin
lovevb12316-Mar-13 6:47
memberlovevb12316-Mar-13 6:47 
QuestionInterface for mocking Pin
MartinWager6-Feb-13 23:57
memberMartinWager6-Feb-13 23:57 
AnswerRe: Interface for mocking Pin
Simon McKenzie7-Feb-13 12:57
memberSimon McKenzie7-Feb-13 12:57 
QuestionParse problem Pin
schurig31-Jan-13 23:53
memberschurig31-Jan-13 23:53 
AnswerRe: Parse problem Pin
BrandonOrding7-Feb-13 16:38
memberBrandonOrding7-Feb-13 16:38 
GeneralRe: Parse problem Pin
Simon McKenzie7-Feb-13 16:51
memberSimon McKenzie7-Feb-13 16:51 
AnswerRe: Parse problem Pin
Simon McKenzie7-Feb-13 16:46
memberSimon McKenzie7-Feb-13 16:46 
BugTweaks needed to make this work with Blackberry images Pin
stevehiner10-Dec-12 13:39
memberstevehiner10-Dec-12 13:39 
First of all, thanks for contributing this to the community. I love what you've done. Unfortunately it doesn't work with the images I have that were taken on Blackberry devices. I've found a couple issues. I don't know enough about RAW exif data to guess if these are bugs in ExifLib or in how the Blackberry writes the exif data but I wouldn't be surprised if Blackberry isn't quite meeting the spec. I have found that Windows 7 will display the Exif data in the image properties.

In these files I have found it throws an index error in the last call to CatalogueIFD made from ExifReader.CreateTagIndex. The issue appears to be that the entryCount gets set to 18761 on the first ReadUShort call. I'm guessing there really aren't 18761 entries. That causes the fileStream position to eventually exceed the length of the file such that the call to ReadUShort throws an ArgumentOutOfRangeException error. I fixed it by dropping:
if (fileStream.Position > fileStream.Length - 2)
    break;
right before the ReadUShort call in the loop. My guess is that there's a better way to handle this because I would think this means it's going to read the entire file 2 bytes at a time when it's really not needed. Is there a sanity check we can put on that first
ushort entryCount = ReadUShort();
to make sure it doesn't pull back an invalid value?

Also, I just ran the speed test and the results don't look good. System.Drawing was able to read 488 images per second but ExifLib only got 51 per second. I'm guessing that's because ExifLib is reading the entire file due to the huge entryCount.

There's a minor issue is in the test app's frmMain.btnPopulate_Click. In the loop that runs through all the available fields when it gets to DeviceSettingDescription it throws an error when extracting the substring because renderedTag is zero length. renderedTag is zero length because the uint array in DeviceSettingDescription is zero length. I fixed that one by adding a length check before the substring call.

The Exif data lists the Software as "Rim Exif Version1.00a" if that helps at all.
Steve

GeneralRe: Tweaks needed to make this work with Blackberry images Pin
Simon McKenzie10-Dec-12 13:47
memberSimon McKenzie10-Dec-12 13:47 
GeneralRe: Tweaks needed to make this work with Blackberry images Pin
stevehiner10-Dec-12 13:51
memberstevehiner10-Dec-12 13:51 
GeneralRe: Tweaks needed to make this work with Blackberry images Pin
Simon McKenzie10-Dec-12 20:10
memberSimon McKenzie10-Dec-12 20:10 
GeneralRe: Tweaks needed to make this work with Blackberry images Pin
stevehiner11-Dec-12 7:23
memberstevehiner11-Dec-12 7:23 
GeneralRe: Tweaks needed to make this work with Blackberry images Pin
Simon McKenzie11-Dec-12 12:14
memberSimon McKenzie11-Dec-12 12:14 
QuestionWrite Support Pin
RadarRambox30-Nov-12 3:16
memberRadarRambox30-Nov-12 3:16 
AnswerRe: Write Support Pin
Simon McKenzie1-Dec-12 11:47
memberSimon McKenzie1-Dec-12 11:47 
AnswerRe: Write Support Pin
RadarRambox2-Dec-12 20:52
memberRadarRambox2-Dec-12 20:52 
GeneralMy vote of 5 Pin
reisenklaus14-Nov-12 12:08
memberreisenklaus14-Nov-12 12:08 
GeneralRe: My vote of 5 Pin
Simon McKenzie14-Nov-12 14:56
memberSimon McKenzie14-Nov-12 14:56 
GeneralRe: My vote of 5 Pin
Simon McKenzie14-Nov-12 19:05
memberSimon McKenzie14-Nov-12 19:05 
GeneralRe: My vote of 5 Pin
reisenklaus15-Nov-12 10:30
memberreisenklaus15-Nov-12 10:30 
Questionweb - File is not a valid JPEG [modified] Pin
nanonerd12-Nov-12 8:06
membernanonerd12-Nov-12 8:06 
AnswerRe: web - File is not a valid JPEG Pin
nanonerd12-Nov-12 11:17
membernanonerd12-Nov-12 11:17 
AnswerRe: web - File is not a valid JPEG Pin
Simon McKenzie12-Nov-12 12:32
memberSimon McKenzie12-Nov-12 12:32 
QuestionGreat library Pin
fallenstd5-Nov-12 2:39
memberfallenstd5-Nov-12 2:39 
QuestionRun FxCop and sign assembly using a strong name Pin
LittleBlueBird28-Oct-12 7:06
memberLittleBlueBird28-Oct-12 7:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 22 Sep 2014
Article Copyright 2009 by Simon McKenzie
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid