Skip to content

Instantly share code, notes, and snippets.

@pepijn-devries
Last active January 20, 2016 11:56
Show Gist options
  • Save pepijn-devries/537402632677e23710a1 to your computer and use it in GitHub Desktop.
Save pepijn-devries/537402632677e23710a1 to your computer and use it in GitHub Desktop.
# function to get a parameter value from EXIF code,
# x = a vector of character strings representing the EXIF codes of a file
# parameter = character string representing the parameter
# for which you want to extract the value
# the literal character string is returned for the requested parameter
get_EXIF_value <- function(x, parameter)
{
line <- x[grepl(paste("EXIF_", parameter, "=", sep = ""), x)]
if (!is.null(line) && length(line) > 0)
{
pos <- gregexpr("=", line, fixed = T)[[1]]
pos <- pos[length(pos)]
line <- substr(line, pos + 1, nchar(line))
line <- gsub("[(]|[)]", "", unlist(strsplit(line, "([)]\\s+[(])|[)][()]")))
}
return(line)
}
# function to get the longitude and latitude from the
# character string obtained with the function above
# x = a character string with the coordinates
get_EXIF_coordinate <- function(x)
{
lat <- get_EXIF_value(x, "GPSLatitude")
lat <- as.numeric(lat)
lat <- lat[1] + lat[2]/60 + lat[3]/(60*60)
latref <- get_EXIF_value(x, "GPSLatitudeRef")
lat <- ifelse(toupper(latref) == "S", -lat, lat)
if (length(lat) == 0) lat <- NA
lon <- get_EXIF_value(x, "GPSLongitude")
lon <- as.numeric(lon)
lon <- lon[1] + lon[2]/60 + lon[3]/(60*60)
lonref <- get_EXIF_value(x, "GPSLongitudeRef")
lon <- ifelse(toupper(lonref) == "W", -lon, lon)
if (length(lon) == 0) lon <- NA
return (c(lon, lat))
}
# for each file obtain the EXIF codes and extract the coordinates
GPStags <- apply(array(file_info$file.name), 1, function(x) {
EXIF_code <- NULL
try (EXIF_code <- attr(GDALinfo(x), "mdata"), silent = T)
if (is.null(EXIF_code)) return(c(NA, NA)) else return(get_EXIF_coordinate(EXIF_code))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment