mini_magick snippets

How to add a watermark to pictures with MiniMagick and Ruby

Tagged watermark, overlay, caption, mini_magick, ruby, gravity, draw  Languages ruby

This code can be used to add a watermark to pictures:

require 'rubygems'
require 'mini_magick'

# Read the image
img = MiniMagick::Image.from_file("the_picture.jpg")

# 0,0 0,0 = add the watermark at coordinates: x, y, set watermark size to auto with 0,0
img.draw 'image Over 0,0 0,0 "the_watermark.gif"'

img.write("watermarked_image.jpg")

How to add a watermark to the bottom-left corner?

To add a watermark to the bottom-left corner, you need to use the combine_options method to pass more than one command plus parameters to MiniMagick (gravity and draw commands):

require 'rubygems'
require 'mini_magick'

img = MiniMagick::Image.from_file("the_image.jpg")

img.combine_options do |c|
  c.gravity 'SouthWest'
  c.draw 'image Over 0,0 0,0 "the_watermark.gif"'
end

img.write("new.jpg")

Troubleshooting

See mogrify's documentation for details on how to use the draw command.

If you get this error it might mean that mogrify can't find the watermark image, or that the syntax is incorrect:

mogrify: Non-conforming drawing primitive definition image'.

How to add a text caption to an image with MiniMagick and Ruby

Tagged mini_magick, ruby, caption, text  Languages ruby
require 'rubygems'
require 'mini_magick'

img = MiniMagick::Image.from_file("jpeg.jpg")

img.combine_options do |c|
  c.gravity 'Southwest'
  c.draw 'text 10,10 "whatever"'
  c.font '-*-helvetica-*-r-*-*-18-*-*-*-*-*-*-2'
  c.fill("#FFFFFF")
end

img.write("new.jpg")

How to add a watermark to images using MiniMagick, attachment_fu and Ruby

Tagged attachment_fu, mini_magick, ruby, watermark  Languages ruby

Use this snippet to add a watermark to an image, after the image is uploaded:

class Image
  .
  has_attachment ...
  .
  .
  after_attachment_saved do |record|    
    # Don't add watermarks to thumbnails
    if record.thumbnail.nil?
      full_path = File.join(RAILS_ROOT, 'public/', record.public_filename)
      
      img = MiniMagick::Image.from_file(full_path)
      
      width = img[:width]
      height = img[:height]
      
      if width > 150 && height > 150
        img.combine_options do |c|
          c.gravity 'SouthWest'
          # This is RAILS_ROOT/images/watermark.gif
          c.draw "image Over 0,0 0,0 \"images/watermark.gif\""
        end

        img.write(full_path)
        
      end
    end
    
  end

Note that after_attachment_saved is a callback added by attachment_fu, use after_save if you're not using attachment_fu.