The best way to do this is to implement a custom processor. That way you can implement your logic and decide when to change the image the way you want.
See an example implementation of a custom processor. In my case I needed to apply a watermark on the images.
lib/paperclip_processors/watermark.rb
module Paperclip
class Watermark < Thumbnail
attr_accessor :format, :watermark_path, :watermark_gravity, :watermark_dissolve
def initialize file, options = {}, attachment = nil
super
@file = file
@format = options[:format]
@watermark_path = options[:watermark_path]
@watermark_gravity = options[:watermark_gravity].nil? ? "center" : options[:watermark_gravity]
@watermark_dissolve = options[:watermark_dissolve].nil? ? 40 : options[:watermark_dissolve]
@current_format = File.extname(@file.path)
@basename = File.basename(@file.path, @current_format)
end
def make
return @file unless watermark_path
dst = Tempfile.new([@basename, @format].compact.join("."))
dst.binmode
command = "composite"
params = "-gravity #{@watermark_gravity} -dissolve #{@watermark_dissolve} #{watermark_path} #{fromfile} #{tofile(dst)}"
begin
success = Paperclip.run(command, params)
rescue PaperclipCommandLineError
raise PaperclipError, "There was an error processing the watermark for #{@basename}"
end
dst
end
def fromfile
"\"#{ File.expand_path(@file.path) }[0]\""
end
def tofile(destination)
"\"#{ File.expand_path(destination.path) }[0]\""
end
end
end
models/image.rb
has_attached_file :file,
processors: [:thumbnail, :watermark],
styles: {
layout: "100%",
preview: {geometry: "900x900>", watermark_path: "#{Rails.root}/app/assets/images/watermarks/watermark_200.png"},
thumbnail: "300x300>",
miniature: "150x150>"
},
convert_options: {
layout: "-units PixelsPerInch -density 100",
preview: "-units PixelsPerInch -density 72",
thumbnail: "-units PixelsPerInch -density 72",
miniature: "-units PixelsPerInch -density 72"
}
You can refer to the documentation for custom processors:
https://github.com/thoughtbot/paperclip#custom-attachment-processors