We are Designers, We are Developers,We are Thinkers,
We are Strategists

Watermarking an image using paperclip gem

 
  • 0
1

You can brand all the images present in your application by placing your official logo as watermark on images. This can be done in a programmatic manner using a paperclip gem.

Requirements:
• Add paperclip gem to your ruby on rails application and install all the dependencies like image magick.

Implementation:
• Choose a model and add image attribute columns by following paperclip documentation.
• Using paperclip options you can easily define different size of images within the model.
• Paperclip allows you to add your custom processor to deal with the images and its sizes.
• If you have multiple sizes of images then you can workout the changes on the original image by adding a custom processor. So that the other images will do have a watermark image correspondingly.
• Create a processor and place in your library folder of your application. If you have multiple processors then it is suggested to have a folder for processors.

Path:RAILS_APP/lib/paperclip_processors/watermark.rb
module Paperclip
class Watermark < Processor
    # Handles watermarking of images that are uploaded.
attr_accessor :current_geometry, :target_geometry, :format, :whiny, :convert_options, :watermark_path, :overlay, :position
def initialize file, options = {}, attachment = nil
super
geometry          = options[:geometry]
      @file             = file
ifgeometry.present?
        @crop             = geometry[-1,1] == '#'
end
      @target_geometry  =Geometry.parse geometry
      @current_geometry = Geometry.from_file @file
      @convert_options  = options[:convert_options]
      @whiny            = options[:whiny].nil? ? true : options[:whiny]
      @format           = options[:format]
      @watermark_path   = options[:watermark_path]
      @dissolve         = options.fetch(:watermark_dissolve, 70)
      @position         = options[:position].nil? ? "SouthEast" : options[:position]
      @overlay          = options[:overlay].nil? ? true : false
      @current_format   = File.extname(@file.path)
      @basename         = File.basename(@file.path, @current_format)
end
    # TODO: extend watermark
    # Returns true if the +target_geometry+ is meant to crop.
def crop?
      @crop
end
    # Returns true if the image is meant to make use of additional convert options.
defconvert_options?
not @convert_options.blank?
end
    # Performs the conversion of the +file+ into a watermark. Returns the Tempfile
    # that contains the new image.
def make
dst = Tempfile.new([@basename, @format].compact.join("."))
dst.binmode
command = "convert"
params = [fromfile]
params += transformation_command
params<<tofile(dst)
begin
success = Paperclip.run(command, params.flatten.compact.collect{|e| "'#{e}'"}.join(" "))
rescue Paperclip::Errors::CommandNotFoundError
raise Paperclip::Errors::CommandNotFoundError, "There was an error resizing and cropping #{@basename}" if @whiny
end
ifwatermark_path
command = "composite"
command += " -dissolve #{@dissolve}"
params = %W[-gravity #{@position} #{watermark_path} #{tofile(dst)}]
params<<tofile(dst)
begin
success = Paperclip.run(command, params.flatten.compact.collect{|e| "'#{e}'"}.join(" "))
rescue Paperclip::Errors::CommandNotFoundError
raise Paperclip::Errors::CommandNotFoundError, "There was an error processing the watermark for #{@basename}" if @whiny
end
end
dst
end
deffromfile
File.expand_path(@file.path)
end
deftofile(destination)
File.expand_path(destination.path)
end
deftransformation_command
if @target_geometry.present?
scale, crop = @current_geometry.transformation_to(@target_geometry, crop?)
trans = %W[-resize #{scale}]
trans += %W[-crop #{crop} +repage] if crop
trans<<convert_options if convert_options?
trans
end
end
end
end

• By using this module, you can manipulate the image to handle watermarking.
• Your model cant call any of the method in the module since its out of model scope. You can require the module by specifying require    paperclip_processors/watermark’ on top of your model inside the class.
• Once after requiring the module, you can able to call the processor on to your image with various options.
• You can place your desired image/logo in public folder.
• Specify the following options in your model inorder to get the watermark on the uploaded image.

:original => {		
			:processors => [:watermark],
			:watermark_path => "#{Rails.root}/public/images/logo-home-new.png",
			:position => 'NorthWest',
			:watermark_dissolve => 90,
			:auto_orient    => false
		}

• Here the processors option in the original hash uses the customized watermark class.
• Watermark_path should have the watermark image complete url. This image will come on uploads.
• The position option is where the watermark image will get pasted. For now, the watermark image comes on left-top    of the uploaded      image, refer the documentation of image magick for various values to pass.
• Auto orient adjusts an image so that its orientation is suitable for viewing. Currently it is set to false.
• After all configurations are done, the image uploads will get a watermark present on them.
• For adding watermarks to existing images in your model, you can try as below,

ModelName.find_eachdo|rec|
rec.image_or_avatar.reprocess!
end

Note: Running above command on your model will convert all the images to be watermarked.

Leave a Reply