Skip to content

Instantly share code, notes, and snippets.

@foxweb
Last active June 19, 2020 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save foxweb/d84e7bf8277bf9407b778721f81e57e0 to your computer and use it in GitHub Desktop.
Save foxweb/d84e7bf8277bf9407b778721f81e57e0 to your computer and use it in GitHub Desktop.
Extract GPS-coordinates from JPEG with Ruby and imagemagick
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
@foxweb
Copy link
Author

foxweb commented Jun 19, 2020

Extract GPS-coordinates from JPEG with Ruby and imagemagick.

Usage:
GpsParser.new('~/Downloads/IMG_8494.jpeg').converted_gps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment