As described in the options below, PaperClip gives you a lot of features by appending special characters after the image dimensions:

  • Ignore Aspect Ratio (‘!’)
  • Only Shrink Larger (‘>’)
  • Only Enlarge Smaller (‘<‘)
  • Fill Given Area (‘^’)
  • Percentage Resize (‘%’)
  • Pixel Count Limit (‘@’)

But sometimes, this options are not enough, and you may prefer cropping the image with exact coordinates before saving it.

I’ve recently used JCrop, a small JS library that allows you to choose a region of an image and send x, y, weight and height to serverside. Afterwards, I needed to process the uploaded images with paperclip and for that situations I created a paperclip processor based on the default “thumbnail” processor and overriding transformation_command as shown below:

 

module Paperclip
  class Cropper < Thumbnail

    def initialize(file, options = {}, attachment = nil)
      super
      @current_geometry.width = target.crop_w
      @current_geometry.height = target.crop_h
    end

    def target
      @attachment.instance
    end

    def transformation_command
      crop_command = [ "-crop",
        "#{target.crop_w.to_i}x#{target.crop_h.to_i}+#{target.crop_x.to_i}+#{target.crop_y.to_i}",
"+repage"
        ]
      crop_command + super
    end
  end
end