Monday, May 16, 2011

Calculating an Images Orientation using Paperclip


If you ever need to know if an image is portrait or landscape in orientation, you can do the following (assuming you have an orientation attribute on your model:
class Image < ActiveRecord::Base
# Paperclip
has_attached_file :file

# Callbacks
before_create :set_orientation

protected

def set_orientation
original_file = self.file.to_file(:original)
dimensions = Paperclip::Geometry.from_file(original_file)
self.orientation = (dimensions.width > dimensions.height) ? 'landscape' : 'portrait'
end
end

1 comment:

  1. I think, that it's more pretty

    self.orientation = Paperclip::Geometry.from_file(self.data.to_file).horizontal? ? 'horizontal' : 'vertical'

    ReplyDelete