A ruby wrapper for ImageMagick or GraphicsMagick command line.
I was using RMagick and loving it, but it was eating up huge amounts of memory. Even a simple script would use over 100MB of RAM. On my local machine this wasn't a problem, but on my hosting server the ruby apps would crash because of their 100MB memory limit.
Using MiniMagick the ruby processes memory remains small (it spawns ImageMagick's command line program mogrify which takes up some memory as well, but is much smaller compared to RMagick). See Thinking of switching from RMagick? below.
MiniMagick gives you access to all the command line options ImageMagick has (found here).
ImageMagick or GraphicsMagick command-line tool has to be installed. You can check if you have it installed by running
$ convert -version
Version: ImageMagick 6.8.9-7 Q16 x86_64 2014-09-11 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2014 ImageMagick Studio LLC
Features: DPC Modules
Delegates: bzlib fftw freetype jng jpeg lcms ltdl lzma png tiff xml zlibMiniMagick has been tested on following Rubies:
- MRI 1.9.3
- MRI 2.0
- MRI 2.1
- MRI 2.2
- Rubinius
- JRuby (1.7.18 and later)
Add the gem to your Gemfile:
gem "mini_magick"Let's first see a basic example of resizing an image.
image = MiniMagick::Image.open("input.jpg")
image.path #=> "/var/folders/k7/6zx6dx6x7ys3rv3srh0nyfj00000gn/T/magick20140921-75881-1yho3zc.jpg"
image.resize "100x100"
image.format "png"
image.write "output.png"MiniMagick::Image.open makes a copy of the image, and further methods modify
that copy (the original stays untouched). We then
resize
the image, and write it to a file. The writing part is necessary because
the copy is just temporary, it gets garbage collected when we lose reference
to the image.
MiniMagick::Image.open also accepts URLs.
image = MiniMagick::Image.open("http://example.com/image.jpg")
image.contrast
image.write("from_internets.jpg")On the other hand, if we want the original image to actually get modified,
we can use MiniMagick::Image.new.
image = MiniMagick::Image.new("input.jpg")
image.path #=> "input.jpg"
image.resize "100x100"
# No calling #write, because it's no a copyWhile using methods like #resize directly is convenient, if we use more
methods in this way, it quickly becomes inefficient, because it calls the
command on each methods call. MiniMagick::Image#combine_options takes
multiple options and from them builds one single command.
image.combine_options do |b|
b.resize "250x200>"
b.rotate "-90"
b.flip
end # the command gets executedAs a handy shortcut, MiniMagick::Image.new also accepts an optional block
which is used to combine_options.
image = MiniMagick::Image.new("input.jpg") do |b|
b.resize "250x200>"
b.rotate "-90"
b.flip
end # the command gets executedThe yieled builder is an instance of MiniMagick::Tool::Mogrify. To learn more
about its interface, see Metal below.
A MiniMagick::Image has various handy attributes.
image.type #=> "JPEG"
image.mime_type #=> "image/jpeg"
image.width #=> 250
image.height #=> 300
image.dimensions #=> [250, 300]
image.size #=> 3451 (in bytes)
image.colorspace #=> "DirectClass sRGB"
image.exif #=> {"DateTimeOriginal" => "2013:09:04 08:03:39", ...}
image.resolution #=> [75, 75]
image.signature #=> "60a7848c4ca6e36b8e2c5dea632ecdc29e9637791d2c59ebf7a54c0c6a74ef7e"If you need more control, you can also access raw image attributes:
image["%[gamma]"] # "0.9"To get the all information about the image, MiniMagick gives you a handy method
(which just converts the output from identify -verbose into a Hash):
image.details #=> {"Format" => "JPEG", "Mime type" => "image/jpeg", "Resolution" => "300x300", ...}MiniMagick.configure do |config|
config.cli = :graphicsmagick
config.timeout = 5
endFor a complete list of configuration options, see Configuration.
MiniMagick also allows you to composite images:
first_image = MiniMagick::Image.new("first.jpg")
second_image = MiniMagick::Image.new("second.jpg")
result = first_image.composite(second_image) do |c|
c.compose "Over" # OverCompositeOp
c.geometry "+20+20" # copy second_image onto first_image from (20, 20)
end
result.write "output.jpg"For multilayered images you can access its layers.
gif.frames #=> [...]
pdf.pages #=> [...]
psd.layers #=> [...]
gif.frames.each_with_index do |frame, idx|
frame.write("frame#{idx}.jpg")
endBy default, MiniMagick validates images each time it's opening them. It
validates them by running identify on them, and see if ImageMagick finds
them valid. This adds slight overhead to the whole processing. Sometimes it's
safe to assume that all input and output images are valid by default and turn
off validation:
MiniMagick.configure do |config|
config.validate_on_create = false
config.validate_on_write = false
endYou can test whether an image is valid:
image.valid?
image.validate! # raises MiniMagick::Invalid if image is invalidWhen things go wrong and commands start failing, you can set the debug mode:
MiniMagick.configure do |config|
config.debug = true
endIn this mode every command that gets executed in the shell will be written to stdout.
Default CLI is ImageMagick, but if you want to use GraphicsMagick, you can specify it in configuration:
MiniMagick.configure do |config|
config.cli = :graphicsmagick
endIf you're a real ImageMagick guru, you might want to use GraphicsMagick only
for certain processing blocks (because it's more efficient), or vice versa. You
can acomplish this with .with_cli:
MiniMagick.with_cli(:graphicsmagick) do
# Some processing that GraphicsMagick is better at
endIf you want to be close to the metal, you can use ImageMagick's command-line tools directly.
MiniMagick::Tool::Mogrify.new do |mogrify|
mogrify.resize("100x100")
mogrify.negate
mogrify << "image.jpg"
end #=> `mogrify -resize 100x100 -negate image.jpg`
# OR
mogrify = MiniMagick::Tool::Mogrify.new
mogrify.resize("100x100")
mogrify.negate
mogrify << "image.jpg"
mogrify.call #=> `mogrify -resize 100x100 -negate image.jpg`This way of using MiniMagick is highly recommended if you want to maximize performance of your image processing. Here are some of the features.
The most basic way of building a command is appending strings:
MiniMagick::Tool::Convert.new do |convert|
convert << "input.jpg"
convert.merge! ["-resize", "500x500", "-negate"]
convert << "output.jpg"
endNote that it's important that everything that in the command-line you would with a space you pass here as a separate argument
# GOOD
convert << "-resize" << "500x500"
# BAD
convert << "-resize 500x500"Shell escaping is also handled for you. If an option has a value that has spaces inside it, just pass it as a regular string.
convert << "-distort"
convert << "Perspective"
convert << "0,0,0,0 0,45,0,45 69,0,60,10 69,45,60,35"convert -distort Perspective '0,0,0,0 0,45,0,45 69,0,60,10 69,45,60,35'
Instead of passing in options directly, you can use Ruby methods:
convert.resize("500x500")
convert.rotate(90)
convert.distort("Perspective", "0,0,0,0 0,45,0,45 69,0,60,10 69,45,60,35")MiniMagick knows which options each tool has, so you will get an explicit
NoMethodError if you happen to have mispelled an option.
Every method call returns self, so you can chain them to create logical groups.
MiniMagick::Tool::Convert.new do |convert|
convert << "input.jpg"
convert.clone(0).background('gray').shadow('80x5+5+5')
convert.negate
convert << "output.jpg"
endMiniMagick::Tool::Convert.new do |convert|
convert << "input.jpg"
convert.repage.+
convert.distort.+("Perspective", "more args")
endconvert input.jpg +repage +distort Perspective 'more args'
MiniMagick::Tool::Convert.new do |convert|
convert << "wand.gif"
convert.stack do |stack|
stack << "wand.gif"
stack.rotate(30)
end
convert << "images.gif"
endconvert wand.gif \( wand.gif -rotate 90 \) images.gif
This gem raises an error when ImageMagick returns a nonzero exit code. Sometimes, however, ImageMagick returns nonzero exit codes when the command actually went ok. In these cases, to avoid raising errors, you can add the following configuration:
MiniMagick.configure do |config|
config.whiny = false
endIf you're using the metal version, you can pass the whiny value to the
constructor:
MiniMagick::Tool::Identify.new(false) do |b|
b.help
endIt can happen that, when dealing with very large images, the process runs out of
memory, and Errno::ENOMEM is raised in your code. In that case try installing
the posix-spawn gem, and tell MiniMagick
to use it when executing shell commands.
MiniMagick.configure do |config|
config.shell_api = "posix-spawn"
endUnlike RMagick, MiniMagick is a much thinner wrapper around ImageMagick.
- To piece together MiniMagick commands refer to the Mogrify
Documentation. For instance
you can use the
-flopoption asimage.flop. - Operations on a MiniMagick image tend to happen in-place as
image.trim, whereas RMagick has both copying and in-place methods likeimage.trimandimage.trim!. - To open files with MiniMagick you use
MiniMagick::Image.openas you wouldMagick::Image.read. To open a file and directly edit it, useMiniMagick::Image.new.