Resizing (to fill) and cropping images with Paperclip :convert_options

It has been quite a while since I’ve used the Paperclip gem by ThoughtBot. I have a very simple model called Photo which has an image attribute acting as the attachment:

class Photo < ActiveRecord::Base
  attr_accessible :image
  has_attached_file :image,
    styles: {
      thumbnail: '200x200^',
      preview: '800x800^'
    convert_options: {
      thumbnail: " -gravity center -crop '200x200+0+0'",
      preview: " -gravity center -crop '800x800+0+0'"
  default_url: "/images/:style/missing.png"

For some reason I couldn’t remember how to resize images to fit neatly within a square, but after fiddling around this totally works:

  • 200×200^: This sets the output geometry to 200×200 pixels but the shortest side will be 200 pixels.
  • convert_options: This adds the extra options to:
    • -gravity center: First center the image. It’s important this is first!
    • -crop ‘200×200+0+0’: Then crop the image into a 200×200 square with 0,0 as the offset.