[Awesome Ruby Gem] Use imagemagick library and minimagick gem to process images in Ruby
minimagick
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).
Prerequisites
These prerequisites are required for the latest version of RMagick.
On Ubuntu, you can run:
1 | sudo apt-get install libmagickwand-dev |
On Centos, you can run:
1 | sudo yum install gcc ImageMagick-devel make which |
On Arch Linux, you can run:
1 | pacman -Syy pkg-config imagemagick |
On Alpine Linux, you can run:
1 | apk add pkgconfig imagemagick imagemagick-dev imagemagick-libs |
On macOS, you can run:
1 | brew install pkg-config imagemagick |
Installation
You can install it as a gem:
1 | gem install mini_magick |
or add it into a Gemfile (Bundler):
1 | # Gemfile |
Then, run bundle install
.
1 | bundle install |
Usage
Let’s first see a basic example of resizing an image.
1 | require "mini_magick" |
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, and options passed in will be forwarded to open-uri.
1 | image = MiniMagick::Image.open("http://example.com/image.jpg") |
On the other hand, if we want the original image to actually get modified, we can use MiniMagick::Image.new
.
1 | image = MiniMagick::Image.new("input.jpg") |
Combine options
While 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.
1 | image.combine_options do |b| |
As a handy shortcut, MiniMagick::Image.new
also accepts an optional block which is used to combine_options.
1 | image = MiniMagick::Image.new("input.jpg") do |b| |
The yielded builder is an instance of MiniMagick::Tool::Mogrify
.
Attributes
A MiniMagick::Image
has various handy attributes.
1 | image.type #=> "JPEG" |
If you need more control, you can also access raw image attributes:
1 | image["%[gamma]"] # "0.9" |
To get the all information about the image, MiniMagick gives you a handy method which returns the output from identify -verbose
in hash format:
1 | image.data #=> |
Note that MiniMagick::Image#data
is supported only on ImageMagick 6.8.8-3 or above, for GraphicsMagick or older versions of ImageMagick use MiniMagick::Image#details
.
Pixels
With MiniMagick you can retrieve a matrix of image pixels, where each member of the matrix is a 3-element array of numbers between 0-255, one for each range of the RGB color channels.
1 | image = MiniMagick::Image.open("image.jpg") |
It can also be called after applying transformations:
1 | image = MiniMagick::Image.open("image.jpg") |
Pixels To Image
Sometimes when you have pixels and want to create image from pixels, you can do this to form an image:
1 | image = MiniMagick::Image.open('/Users/rabin/input.jpg') |
In this example, the returned pixels should now have equal R, G, and B values.
Configuration
1 | MiniMagick.configure do |config| |
For a complete list of configuration options, see Configuration - https://rubydoc.info/github/minimagick/minimagick/MiniMagick/Configuration.
Composite
MiniMagick also allows you to composite images:
1 | first_image = MiniMagick::Image.new("first.jpg") |
Layers/Frames/Pages
For multilayered images you can access its layers.
1 | gif.frames #=> [...] |
Image validation
By 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:
1 | MiniMagick.configure do |config| |
You can test whether an image is valid:
1 | image.valid? |
Logging
You can choose to log MiniMagick commands and their execution times:
1 | MiniMagick.logger.level = Logger::DEBUG |
In Rails you’ll probably want to set MiniMagick.logger = Rails.logger
.
Switching CLIs (ImageMagick <=> GraphicsMagick)
Default CLI is ImageMagick, but if you want to use GraphicsMagick, you can specify it in configuration:
1 | MiniMagick.configure do |config| |
You can also use .with_cli to temporary switch the CLI:
1 | MiniMagick.with_cli(:graphicsmagick) do |
WARNING: If you’re building a multithreaded web application, you should change the CLI only on application startup. This is because the configuration is global, so if you change it in a controller action, other threads in the same process will also have their CLI changed, which could lead to race conditions.
Metal
If you want to be close to the metal, you can use ImageMagick’s command-line tools directly.
1 | MiniMagick::Tool::Magick.new do |magick| |
If you’re on ImageMagick 7, you should probably use MiniMagick::Tool::Magick
, though the legacy MiniMagick::Tool::Convert
and friends will work too. On ImageMagick 6 MiniMagick::Tool::Magick
won’t be available, so you should instead use MiniMagick::Tool::Convert
and friends.
This way of using MiniMagick is highly recommended if you want to maximize performance of your image processing. We will now show the features available.
Appending
The most basic way of building a command is appending strings:
1 | MiniMagick::Tool::Convert.new do |convert| |
Note that it is important that every command you would pass to the command line has to be separated with <<, e.g.:
1 | # GOOD |
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.
1 | convert << "-distort" |
Methods
Instead of passing in options directly, you can use Ruby methods:
1 | convert.resize("500x500") |
MiniMagick knows which options each tool has, so you will get an explicit NoMethodError
if you happen to have mispelled an option.
Chaining
Every method call returns self, so you can chain them to create logical groups.
1 | MiniMagick::Tool::Convert.new do |convert| |
“Plus” options
1 | MiniMagick::Tool::Convert.new do |convert| |
Stacks
1 | MiniMagick::Tool::Convert.new do |convert| |
STDIN and STDOUT
If you want to pass something to standard input, you can pass the :stdin option to #call:
1 | identify = MiniMagick::Tool::Identify.new |
Capturing STDERR
Some MiniMagick tools such as compare output the result of the command on standard error, even if the command succeeded. The result of MiniMagick::Tool#call is always the standard output, but if you pass it a block, it will yield the stdout, stderr and exit status of the command:
1 | compare = MiniMagick::Tool::Compare.new |
References
[1] minimagick/minimagick: mini replacement for RMagick - https://github.com/minimagick/minimagick
[2] mini_magick | RubyGems.org | your community gem host - https://rubygems.org/gems/mini_magick