Saturday, January 24, 2009

Watermarking an image in Rails - Rmagick

class Image < ActiveRecord::Base

require 'RMagick'
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 4.megabytes,
:resize_to => '640x400>',
:thumbnails => { :thumb => '100x100>',:medium => '250x150' }

validates_as_attachment

def watermark_image
dst = Magick::Image.read("#{RAILS_ROOT}/public/#{self.public_filename}").first
src = Magick::Image.read("#{RAILS_ROOT}/public/images/logo.gif").first
result = dst.composite(src, Magick::CenterGravity, Magick::HardLightCompositeOp)
result.write("#{RAILS_ROOT}/public/#{self.public_filename}")
end

4 comments:

  1. Hi!! but how to call "watermark_image" method? Is it called automatically when you upload pic.?

    ReplyDelete
  2. You can call it after your picture save. i.e. You can call it by callback method 'after_save' in model.

    ReplyDelete
  3. Sorry! i am new for ruby on rails. I understood your code. But, if i want to upload a pic, watermark it and save to database, how is my code gonna be? i am confused with logo.gif.

    ReplyDelete
  4. Thank you! worked like a charm

    ReplyDelete

Contact Me for any help regarding rails/nodejs/php/mysql

Name

Email *

Message *