Skip to content

Instantly share code, notes, and snippets.

@renenw
Last active May 6, 2020 13:59
Show Gist options
  • Save renenw/96136dfe9511151d00022a1c161088f7 to your computer and use it in GitHub Desktop.
Save renenw/96136dfe9511151d00022a1c161088f7 to your computer and use it in GitHub Desktop.
An ActiveStorage analyzer that pulls out GPS and other details
require 'exifr/jpeg'
# Add to your Gemfile: gem 'exifr', '~> 1.3', '>= 1.3.6'
# I created the file in /lib/active_storage/sasa_analyzer.rb
# You will also need to update your application.rb: config.autoload_paths << "#{Rails.root}/lib/active_storage"
# Draws on https://ledermann.dev/blog/2018/05/15/exif-analyzer-for-active-storage/
class SasaAnalyzer < ActiveStorage::Analyzer
ROTATIONS = {
3 => 180,
6 => 90,
8 => -90,
}
def self.accept?(blob)
true
end
def metadata
meta = {}
if blob.image? && blob.filename.extension_without_delimiter=~/jpe?g/i
download_blob_to_tempfile do |file|
meta.merge!(from_exif(file))
end
end
meta
end
private
def from_exif(image)
meta = {}
begin
image = EXIFR::JPEG.new(image.path)
meta[:model] = image.model
meta[:width] = image.width
meta[:height] = image.height
meta[:date_time] = image.date_time
meta[:orientation] = image.orientation.to_sym
meta[:rotation_dregrees] = ROTATIONS[image.orientation.to_i]
if image.gps
meta[:latitude] = image.gps.latitude
meta[:longitude] = image.gps.longitude
meta[:altitude] = image.gps.altitude if image.gps.altitude
end
rescue EXIFR::MalformedImage, EXIFR::MalformedJPEG
end
meta
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment