Last Updated: February 25, 2016
·
2.412K
· mrclmrvn

Paperclip force original image to resize on create

This allows you to keep the original image under a certain dimension on upload, so when you reprocess the image in the future, all styles will be based on the resized original

In this example, the original style is kept at 640px long side.

class Document < ActiveRecord::Base
  # ommitted lines 
  has_attached_file :picture, styles: lambda { |attachment|
    g = attachment.instance.picture_width.blank? && attachment.instance.picture_height.blank? ? {original: "640x640>" } : {}
    g.merge({tiny: '25x25#', thumb: '60x60#', large: '400>'})
  }, path: ":rails_root/public/system/:attachment/:id_partition/:style/:filename",
     url: "/system/:attachment/:id_partition/:style/:filename", :processors => [:cropper, :rotator]
end

You can use an method to replace attachment.instance.picture_width.blank?, to inject the original style via lambda. In my example, I use a picture_width property.

If you upload an image at 2952x2952px, the original will be downsized to 640x640px. So, if you load the image via document.picture.url(:original), it's at 640x640px.