Watermark your images in Rails

March 3, 2009

 
No Gravatar

I’ve been working on a project that requires me to watermark all my images. Here’s a script I put together using rmagick. I plan on releasing a skeleton application that will accept uploaded files and watermark them.

Ideally, I’d like to use paperclip to handle uploading, and write a processor subclass to handle watermarking…unfortunately I’m running into some issues. If anybody wants to lend a hand, I have the public repository up at: http://github.com/ng/paperclip-watermarking-app/tree

require 'RMagick'
 
# load source and watermark images
src = Magick::ImageList.new("source-image.jpg").first
watermark = Magick::Image.read("watermark-image.png").first
 
# create a new, blank image with a height that is the sum of
# the source and watermark
dst = Image.new(src.columns, src.rows+watermark.rows) { self.background_color = 'white' }
 
# place the source image on the blank image
result = dst.composite(src, Magick::NorthGravity, Magick::OverCompositeOp)
 
# place the watermark over the previous transformation
result = result.composite(watermark, Magick::SouthEastGravity, Magick::OverCompositeOp)
 
# write it out
result.write('watermarked-image.jpg')
blog comments powered by Disqus