Last active
June 19, 2020 14:04
-
-
Save foxweb/d84e7bf8277bf9407b778721f81e57e0 to your computer and use it in GitHub Desktop.
Extract GPS-coordinates from JPEG with Ruby and imagemagick
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GpsParser | |
def initialize(file_path) | |
@file_path = file_path | |
end | |
def converted_gps | |
return if raw_exif_data.empty? | |
{ | |
latitude: float_gps(:GPSLatitude, :GPSLatitudeRef), | |
longitude: float_gps(:GPSLongitude, :GPSLongitudeRef) | |
} | |
end | |
private | |
attr_reader :file_path | |
def raw_exif_data | |
`identify -format '%[exif:GPS*]' #{file_path}`.split("\n") | |
end | |
def exif_data | |
@exif_data ||= raw_exif_data.reduce({}) do |result, row| | |
name, value = row.split('=') | |
key = name.split(':').last | |
result.merge(key.to_sym => value) | |
end | |
end | |
# convert GPS coordinates to float | |
def float_gps(type, ref) | |
deg, min, sec = exif_data[type].split(', ').map(&method(:rational_to_float)) | |
result = deg + min / 60 + sec / 3600 | |
%w[S W].include?(exif_data[ref]) ? -result : result | |
end | |
def rational_to_float(str) | |
numerator, denominator = str.split('/') | |
Rational(numerator, denominator).to_f | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Extract GPS-coordinates from JPEG with Ruby and imagemagick.
Usage:
GpsParser.new('~/Downloads/IMG_8494.jpeg').converted_gps