Auto Orienting Images with Paperclip

Hi folks, have you ever had some issue with image's orientation while performing uploads with Paperclip gem?

This week after taking some photos with an iPad app and uploading them to my Rails site I realized that something wasn't good.

The photos were taken in the vertical orientation, however, they were being displayed in horizontal on my site.

Looking into thumbnails generated by Paperclip I saw they were in the correct orientation. Just the original ones were wrong.

I found out that there is an ImageMagick's option called auto-orient which enables us to correct the orientation.

Paperclip give us a way to pass command line options to ImageMagick like below:

has_attached_file :logo, styles: { original: {convert_options: '-auto-orient'} }

How I would need to repeat this code in some models, I chose to place it in my config/initializers/paperclip.rb file together with others already existing default options:

# ...
Paperclip::Attachment.default_options[:storage] = :s3
Paperclip::Attachment.default_options[:s3_credentials] = "#{Rails.root}/config/s3.yml"
Paperclip::Attachment.default_options[:styles] = lambda { |attachment|
attachment.content_type.index("image/") == 0 ? {original: {convert_options: "-auto-orient"}} : {}
}

But wait! Look that we are doing some checking before adding this options, it is required to avoid problems while trying to auto orient files that aren't images (like pdf).

I hope it helps.

See you.

Written on August 4, 2015

Share: