Extract the GPS information of an image

In one of my current project I need some basic image operations and want to use as few third part libraries as possible. Especially I do not want to be dependent from server side libraries like ImageMagick.

In the following blog entries I want to show a java implementation for some frequently uses image operations/tranfomrations. This time I want to go into detail how to extract the GPS information from an image, if exists.

Before continuing it should be noted, that this project stores all files in the database, for this, I use a FileRecord class which consists of the following attributes:

private long pid;
private Date creationDate;
private String filename;
private String filetyp;
private int size;
private byte[] file;
private String hash;
private boolean deleted;

As already mentioned I wanted to use as few third part libraries as possible, but the Exif information of the image is a basic requirment which is needed to continue. For this task I decided to use the metadata-extractor java library, which I already used in another project, and I really like because of its simplicity.

But now let us start with the implemenation of the operations:

public static Metadata getImageMetadata(FileRecord image) throws ImageProcessingException, IOException {
String typ = image.getFiletyp().split("/")[0]; // The file typ
if(typ.equals("image")) {
InputStream in = new ByteArrayInputStream(image.getFile());
Metadata metadata = ImageMetadataReader.readMetadata(in);

return metadata;
} else
return null;

public static String[] getGeoLocation(FileRecord image) throws ImageProcessingException, IOException {
String coordinates[] = new String[3];
Metadata metadata = getImageMetadata(image);
if(metadata != null) {
if (metadata.containsDirectoryOfType(GpsDirectory.class)) {
GpsDirectory gpsDir = metadata.getFirstDirectoryOfType(GpsDirectory.class);
GpsDescriptor gpsDesc = new GpsDescriptor(gpsDir);

// Set Latitude
coordinates[0] = gpsDesc.getGpsLatitudeDescription();
// Set Longitude
coordinates[1] = gpsDesc.getGpsLongitudeDescription();
// Set Altitude
coordinates[2] = gpsDesc.getGpsAltitudeDescription();
return coordinates;

These two methods uses the already mentioned metadata-extractor java library to extract the image metadata, from a given FileRecord if of type “image”. For more information about metada and the library please visit the git-hub page of the developer, the readme is quiet well written.

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *