How to read EXIF and IPTC with Java Image I/O API
The JPEG readers and writers of Java Image I/O API (a.k.a. imageio) and Java Advanced Imaging Image I/O Tools API (a.k.a. JAI imageio) are currently missing support for EXIF and IPTC metadata. I therefore wrote a small sample code that demonstrates how this metadata can be read with imageio.
How it works
The sample follows the principle outlined in the JPEG Metadata Format Specification and Usage Notes, which is a part of the javax.imageio.metadata package description. Here is a pseudo code that follows that principle:
Iterator iter=ImageIO.getImageReadersByFormatName("jpeg");
ImageReader reader=(ImageReader) iter.next();
IIOMetadata metadata=reader.getImageMetadata(0);
String name=reader.getNativeMetadataFormatName()
IIOMetadataNode node=(IIOMetadataNode) reader.getAsTree(name);
IIOMetadataNode exifNode=findUnknownMarkerTag(node, 0xE1);
IIOMetadataNode iptcNode=findUnknownMarkerTag(node, 0xED);
byte[] exif=(byte[]) exifNode.getUserObject();
byte[] iptc=(byte[]) iptcNode.getUserObject();
The function findUnknownMarkerTag() traverse the DOM tree rooted in node till an element with name unknown and an attribute named MarkerTag that parsed to an integer is equal to the argument.
The byte arrays exif and iptc must be further parsed. In the sample code I have used Drew Noake’s excellent metadata-extractor library.
Download, compile and test the sample code
Download and unzip the sample code, e.g.
wget http://www.barregren.se/files/imageioMetadataDemo.zip unzip imageioMetadataDemo.zip
Compile the sample code, e.g.
cd imageioMetadataDemo mkdir bin javac -classpath lib/metadata-extractor-2.3.1.jar -d bin src/se/barregren/imageio/metadata/ImageIOMetadataDemo.java
Run the compiled code, e.g.
java -cp bin:lib/metadata-extractor-2.3.1.jar se.barregren.imageio.metadata.ImageIOMetadataDemo test.jpg
Post new comment