Search code examples
ruby-on-railsimagepaperclipcrop

Paperclip - Conditional cropping by image ratio


I'm using paperclip with ImageMagik. My question is, how can I make paperclip crop images to a certain size only if their ratio is smaller then X.

What i'm looking for is to crop all images to a certain dimesion, except for tall images, which I don't want to crop, simply scale.

My current setup is: "X425"

I would like to have: "615X425#" for non tall images, and "X425" for tall\wide images.

Thanks! Uri


Solution

  • Conditional Formatting

    A while back, we wanted to use conditional styling in Paperclip, and came up with this & have since found this:

    #app/models/attachment.rb
    Class Attachment < ActiveRecord::Base
    
        has_attached_file :image,
            styles: Proc.new { |instance| instance.resize }
    
        private
    
        def resize     
            geo = Paperclip::Geometry.from_file(photo.to_file(:original))
    
            ratio = geo.width/geo.height  
    
            min_width  = 142
            min_height = 119
    
            if ratio > 1
               # Horizontal Image
               final_height = min_height
               final_width  = final_height * ratio
               "#{final_width.round}x#{final_height.round}!"
            else
               # Vertical Image
               final_width  = min_width
               final_height = final_width * ratio
              "#{final_height.round}x#{final_width.round}!"
            end
      end  
    end
    

    I took the resize code from this answer