How to add a watermark to images using MiniMagick, attachment_fu and Ruby
Ruby posted about 1 year ago by christian
Use this snippet to add a watermark to an image, after the image is uploaded:
1 class Image 2 . 3 has_attachment ... 4 . 5 . 6 after_attachment_saved do |record| 7 # Don't add watermarks to thumbnails 8 if record.thumbnail.nil? 9 full_path = File.join(RAILS_ROOT, 'public/', record.public_filename) 10 11 img = MiniMagick::Image.from_file(full_path) 12 13 width = img[:width] 14 height = img[:height] 15 16 if width > 150 && height > 150 17 img.combine_options do |c| 18 c.gravity 'SouthWest' 19 # This is RAILS_ROOT/images/watermark.gif 20 c.draw "image Over 0,0 0,0 \"images/watermark.gif\"" 21 end 22 23 img.write(full_path) 24 25 end 26 end 27 28 end
Note that after_attachment_saved is a callback added by attachment_fu, use after_save if you’re not using attachment_fu.
Installing ImageMagick, mini-magick and rmagick on Mac OS X Leopard
Ruby posted about 1 year ago by christian
I had no success installing ImageMagick and mini-magick with the instructions I found on this page but after some googling I found this blog post, which had the magic commands that worked for me:
1 sudo port install tiff -macosx #disables the linkage with Apple's open gl 2 sudo port install ImageMagick 3 4 sudo gem install rmagick 5 sudo gem install mini_magick
To test mini-magick, open an irb console and paste in the following code:
1 require 'rubygems' 2 require 'mini_magick' 3 4 path = "public/images/0000/0003/logo.jpg" 5 image = MiniMagick::Image.new(path) 6 7 #print width and height 8 puts image[:width] 9 puts image[:height]