Skip to content

Instantly share code, notes, and snippets.

@brenogazzola
Created February 12, 2021 00:25
Show Gist options
  • Save brenogazzola/85d0cd2185b0e372d423bde1ccf4ffab to your computer and use it in GitHub Desktop.
Save brenogazzola/85d0cd2185b0e372d423bde1ccf4ffab to your computer and use it in GitHub Desktop.
Vips based image analyzer for Active Storage
# frozen_string_literal: true
module ActiveStorage
class Analyzer::FastImage < ActiveStorage::Analyzer
def self.accept?(blob)
blob.image?
end
def metadata
read_image do |image|
if rotated_image?(image)
{ width: image.height, height: image.width }
else
{ width: image.width, height: image.height }
end
end
end
private
def read_image
download_blob_to_tempfile do |file|
require 'ruby-vips'
image = Vips::Image.new_from_file(file.path, access: :sequential)
if valid_image?(image)
yield image
else
logger.info "Skipping image analysis because Vips doesn't support the file"
{}
end
end
rescue LoadError
logger.info "Skipping image analysis because the ruby-vips gem isn't installed"
{}
rescue Vips::Error => error
logger.error "Skipping image analysis due to an Vips error: #{error.message}"
{}
end
def rotated_image?(image)
orientation = image.get("exif-ifd0-Orientation")
orientation.include?("Right-top") || orientation.include?("Left-bottom")
end
def valid_image?(image)
image.avg
true
rescue ::Vips::Error
false
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment