Search code examples
ruby-on-railsimageruby-on-rails-4paperclipminimagick

How to crop image manually with paperclip?


I'm building a website with Rails 4.2 and Mongoid. I'm using mongoid-paperclip, and I'm trying to crop an image down to a square while preserving the dimensions of the short side (so the image will fill the full square). Here's my custom processor:

module Paperclip
  class Cropper < Thumbnail
    def initialize(file, options = {}, attachment = nil)
      super
      @preserved_size = [@current_geometry.width, @current_geometry.height].min
      @current_geometry.width = @preserved_size
      @current_geometry.height = @preserved_size
     end

    def target
      @attachment.instance
    end

    def transformation_command
      if crop_command
        crop_command + super.join(' ').sub(/ -crop \S+/, '').split(' ')
      else
        super
      end
    end

    def crop_command
      ["-crop", "#{@preserved_size}x#{@preserved_size}+#{@preserved_size}+#{@preserved_size}"]
    end
  end
end

And the model that it's attached to looks has this line:

has_mongoid_attached_file :image, styles: {square: {processors: [:cropper]}}

But it doesn't seem to work. A version of the image named 'square' is saved, but it's identical to the original. How can I get this to work?


Solution

  • I was able to fix this without using a paperclip processor. In my model, I specified the styles for the image using a lambda:

    has_mongoid_attached_file :image, styles: lambda {|a|
                                                tmp = a.queued_for_write[:original]
                                                return {} if tmp.nil?
                                                geometry = Paperclip::Geometry.from_file(tmp)
                                                preserved_size = [geometry.width.to_i, geometry.height.to_i].min
                                                {square: "#{preserved_size}x#{preserved_size}#"}
                                              }
    

    Note that the # at the end of the dimensions ensured that the cropped image was always the specified dimensions, rather than just scaling down the image.