Skip to content

Instantly share code, notes, and snippets.

@ceneon
Last active August 29, 2015 14:23
Show Gist options
  • Save ceneon/a668cdc626bb1da20c1c to your computer and use it in GitHub Desktop.
Save ceneon/a668cdc626bb1da20c1c to your computer and use it in GitHub Desktop.
Apply watermark over image using Paperclip
has_attached_file :file,
styles: {
detail: {
geometry: "__width__x__height__#",
watermark_path: Rails.root.join("app/assets/images/__watermark_image__.png"),
position: 'Center' # SouthEast, NorthWest, etc
}
}, processors: [:watermark]
# /lib/paperclip_processors/watermark.rb
module Paperclip
class Watermark < Processor
def initialize file, options = {}, attachment = nil
super
@file = file
@attachment = attachment
@whiny = options[:whiny].nil? ? true : options[:whiny]
@format = options[:format]
@current_format = File.extname(@file.path)
@basename = File.basename(@file.path, @current_format)
end
def make
dst = Tempfile.new([@basename, @format].compact.join("."))
dst.binmode
outfile = File.expand_path(dst.path)
if options[:watermark_path]
command = "convert"
params = %W['#{fromfile}']
params += transformation_command
params += %W['#{options[:watermark_path]}' -gravity #{options[:position]} -composite]
params << "'#{tofile(dst)}'"
else
command = "convert"
params = ["'#{fromfile}'"]
params += transformation_command
params << "'#{tofile(dst)}'"
end
begin
Paperclip.run(command, params.join(' '))
rescue ArgumentError, Cocaine::CommandLineError
raise Exception, "There was an error processing the watermark for #{@basename}" if @whiny
end
dst
end
def fromfile
"#{ File.expand_path(@file.path) }[0]"
end
def tofile(destination)
File.expand_path(destination.path)
end
def transformation_command
scale, crop = (Geometry.from_file file).transformation_to((Geometry.parse options[:geometry]), crop?)
trans = %W[-resize '#{scale}']
trans += %W[-crop '#{crop}' +repage] if crop
trans << options[:convert_options] if options[:convert_options]
trans
end
# Returns true if the +target_geometry+ is meant to crop.
def crop?
options[:geometry][-1,1] == '#'
end
# Returns true if the image is meant to make use of additional convert options.
def convert_options?
not options[:convert_options].blank?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment