Last active
May 6, 2020 13:59
-
-
Save renenw/96136dfe9511151d00022a1c161088f7 to your computer and use it in GitHub Desktop.
An ActiveStorage analyzer that pulls out GPS and other details
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
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