You are viewing an archived version of danielfischer.com

 

Watermarking an image in Rails

Published: April 16th, 2007

Need a guide on watermarking an image on Ruby on Rails? Well here’s a quick tip on how to do it!

In a recent task I had to add the ability to add watermarking support when a user uploads a photo. I thought this would be hard, but after some research and some coding, it came out to be rather easy. I got it down in four lines of code. First, as an attachment system, I used attachment_fu. For an image processor, I used RMagick. In my picture model:

def watermark_image
  dst = Magick::Image.read("#{RAILS_ROOT}/public/#{self.public_filename}").first
  src = Magick::Image.read("#{RAILS_ROOT}/config/upshot.png").first
  result = dst.composite(src, Magick::SouthEastGravity, Magick::OverCompositeOp)
  result.write("#{RAILS_ROOT}/public/#{self.public_filename}")
end

Just plug that in, and call an after_safe on :watermark_image in the model. This is so that everytime a user uploads a photo, the watermark_image method is called.

I’m new to rails and attachment_fu can you post your model file code for this.

My model currently looks like this
class Asset :image,
:storage => :file_system,
:thumbnails => { :thumb_sm => [25,25],
:thumb_lg => [50,50],
:small => “150×150>”,
:medium => “300×300>”,
:large => “450×450>”
}

validates_as_attachment

def watermark_image
dst = Magick::Image.read(”#{RAILS_ROOT}/public/#{self.public_filename}”).first
src = Magick::Image.read(”#{RAILS_ROOT}/config/upshot.png”).first
result = dst.composite(src, Magick::SouthEastGravity, Magick::OverCompositeOp)
result.write(”#{RAILS_ROOT}/public/#{self.public_filename}”)
end

Where should i place the after_safe effent because i want all the generated images to have the watermark

gravatar
  • D
  • Sep 25th

It’s after_save in fact …

Cheers,
boris

gravatar
  • Boris
  • Sep 28th

(Please delete my previous post)

Put after_save :watermark_image at the top of your model file.

Example:

class Asset::image
after_save :watermark_image

:storage => :file_system
…blah blah blah, attachment_fu junk…

validates_as_attachment

def watermark_image
…watermark method…
end
end

gravatar
  • PS
  • Apr 29th
Enter your comment

Ready. Set. Go.

In terms of the formatting, you're allowed to use markdown, textile, or basic html; it's truly up to you -- what strikes your fancy?

You don't have to worry about your e-mail address being sold to a russian-spam-mafia. I'm only going to use it for my own weird needs; like asking you out for a date on a lonely night of coding.