Search code examples
ruby-on-railsruby-on-rails-3paperclipjcrop

Rails paperclip generate thumbnail from other style


I'm following the jcrop rails tutorial, but I've hit a snag. What it comes down to is the fact that paperclip is generating the thumbnail from the original file, but I need it to be generated from another style. The original file doesn't have any space between the product shot and the edge of the document. Therefore I can't crop further out. To combat that, I made another style which has white pixel padding. That's what I want to generate the thumbnail from.

# croppable is the one with the padding...it's what shows up in the crop view.
# I want :thumb to be generated from THAT style, not :original.
# When generating from :original, the crop offset/size is screwed because the dimensions of :original don't match :cropped
# and I can't crop beyond the pixel dimensions of :original.
has_attached_file :photo, :styles => {
                    :thumb => { :geometry => "300x300#", :format => :jpg, :processors => [:cropper] },
                    :general => ["150x375", :jpg],
                    :show => ["x425", :jpg],
                    :croppable => ["1200x1200>", :jpg]
        },
        :url  => "/assets/wines/:style/:wine_name",
        :path => ":rails_root/public:url",
        :default_url => ":wine_default",
        :default_path => ":rails_root/public:wine_default",
        :default_style => :show,
        :convert_options => {
            :thumb => '-gravity center -rotate -30',
            :croppable => '-gravity center -extent 1200x1200',
            :general => '-gravity center -extent 150x375 -quality 95',
            :all => '-quality 100 -antialias -flatten -background white -unsharp 0.3x0.3+5+0'
        },
        :processors => [:thumbnail, :compression]

Solution

  • I came across a processor that someone else had made online and used it for myself. Details can be found at http://pjkh.com/articles/speeding-up-thumbnail-generation-with-paperclip/ for advanced usage information.

    recursive_thumbnail.rb (include in lib/paperclip_processors)

    module Paperclip
        class RecursiveThumbnail < Thumbnail
          def initialize file, options = {}, attachment = nil
            super Paperclip.io_adapters.for(attachment.styles[options[:thumbnail] || :original]), options, attachment
          end
        end
    end
    

    and for your model:

    :styles => {
        :croppable => ["1200x1200>", :jpg],
        :show => ["x425", :jpg],
        :general => ["150x375", :jpg],
        :thumb => {
            :geometry => "150x150^",
            :format => :jpg,
            :processors => [:recursive_thumbnail] },
            :thumbnail => :croppable
        }