package albumgen.util;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.Date;
import java.util.Iterator;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifDirectory;
/**
* Class containing utility methods for extracting Exif data from JPEG files.
*/
public class FileUtils {
/**
* Opens the specified JPEG file and looks for a date-stamp under a variety of
* Exif tags.
*
* @param jpegFile
* @return A date if found, otherwise null.
*/
public static Date extractDate(File jpegFile) {
Date date = null;
try {
Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
// iterate through metadata directories
Iterator directories = metadata.getDirectoryIterator();
while (directories.hasNext()) {
Directory directory = (Directory) directories.next();
if (directory instanceof ExifDirectory) {
ExifDirectory exif = (ExifDirectory) directory;
try {
if (exif.containsTag(ExifDirectory.TAG_DATETIME_ORIGINAL)) {
date = exif.getDate(ExifDirectory.TAG_DATETIME_ORIGINAL);
} else if (exif.containsTag(ExifDirectory.TAG_DATETIME)) {
date = exif.getDate(ExifDirectory.TAG_DATETIME);
} else if (exif
.containsTag(ExifDirectory.TAG_DATETIME_DIGITIZED)) {
date = exif.getDate(ExifDirectory.TAG_DATETIME_DIGITIZED);
}
} catch (MetadataException e) {
e.printStackTrace();
}
}
}
} catch (JpegProcessingException ex) {
// Ignore exception and return null. Probably just isn't a Jpeg file!
}
return date;
}
/**
* Copies a file! Efficient-like.
* @param src from here
* @param dest to here
*/
static public void copyFile(File src, File dest) throws IOException {
FileChannel in = null;
FileChannel out = null;
try {
in = new FileInputStream(src).getChannel();
out = new FileOutputStream(dest).getChannel();
in.transferTo(0, in.size(), out);
} finally {
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
// no impl.
}
}
}
}
|