views:

314

answers:

3

Hi, I'm looking for a way to determine image orientation preferably with Paperclip, but is it even possible or do I need to user RMagick or another image library for this?

Case scenario: When a user uploads an image i want to check the orientation/size/dimensions to determine if the image is in portrait/landscape or square and save this attribute to the model.

A: 

When I take a photo with my camera the dimensions of the image are the same regardless if the photo is landscape or portrait. However, my camera is smart enough to rotate the image for me! How thoughtful! The way this work is that is uses something called exif data which is meta data placed on the image by the camera. It includes stuff like: the type of camera, when the photo was taken, orientation etc...

With paperclip you can set up callbacks, specifically what you'll want to do is have a callback on before_post_process that checks the orientation of the image by reading the exif data using a library (you can find a list here: http://blog.simplificator.com/2008/01/14/ruby-and-exif-data/), and then rotating the image clockwise or counterclockwise 90 degrees (you won't know which way they rotated the camera when they took the photo).

I hope this helps!

jonnii
I looked into this and it's also a great solution, although this time the image uploads are by users and I don't really trust their capacity to upload images correctly.
The Tailor
+1  A: 

Thanks for the answer jonnii.

Although I did find what I was looking for in the PaperClip::Geometry module.

This worked find:

class Image < ActiveRecord::Base
  after_save :set_orientation

  has_attached_file :data, :styles => { :large => "685x", :thumb => "100x100#" }
  validates_attachment_content_type :data, :content_type => ['image/jpeg', 'image/pjpeg'], :message => "has to be in jpeg format"

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

This of course makes both vertical and square images have the vertical attribute but that's what I wanted anyway.

The Tailor
+1  A: 
Callmeed