Register now and start sharing your code snippets.
-->
How to add a watermark to images using MiniMagick, attachment_fu and Ruby
Ruby posted 6 months 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.