Skip to content

Example: How to Create a Padded Thumbnail

Mark Evans edited this page Apr 29, 2015 · 1 revision

In this padded thumbnail example, I want to shrink a rectangular image onto a square canvas while maintaining aspect ratio. This would be a great feature to have built in.

Dragonfly.app.configure do
  processor :padded_thumb do |content, dimensions, *args|
    args    = args.first || {}
    bg      = args[:bg] || 'white'
    format  = args[:format] || 'jpeg'
    quality = args[:quality] || 80
    # shell command: 
    #   convert -resize 80x80 -background white -gravity center -extent 80x80 -format jpg -quality 75
    content.process! :convert, "-auto-orient -resize #{dimensions} -background #{bg} -gravity center -extent #{dimensions} -format #{format} -quality #{quality}"
  end
end

To use:

@album.thumb = @album.photo.padded_thumb('100x100')
@album.save

@album.thumb = @album.photo.padded_thumb('100x100', bg: 'black', quality: 90, format: 'png')
@album.save
Clone this wiki locally