[Awesome Ruby Gem] Use imagemagick library and rmagick gem to process images in Ruby
rmagick
RMagick is an interface between the Ruby programming language and the ImageMagick image processing library.
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 rmagick |
or add it into a Gemfile (Bundler):
1 | # Gemfile |
Then, run bundle install
.
1 | bundle install |
Usages
Basic concepts
Let’s look at the RMagick equivalent of “Hello, world”. This program reads an image file named “Cheetah.jpg” and display it on your monitor.
1 | require 'RMagick' |
Reading, writing, and creating images
For example, you can set the background color of a new image to red with the background_color= method, as shown here:
1 | require 'RMagick' |
For example, the following program reads three GIF files and then uses ImageList#write to combine all the images in those files (remember, each input file can contain multiple images) into one animated GIF file.
1 |
|
For example, the following program, read a pdf file and convert to JPG file.
1 | require 'RMagick' |
As an example, here’s the section of the Ruby program that created the circle in the center of the above image.
1 | !# /usr/local/bin/ruby -w |
Annotation
The annotate method draws text on an image. In its simplest form, annotate requires only arguments that describe where to draw the text and the text string.
The following example shows how to use annotate to produce this image.
annotate example
1 |
|
References
[1] rmagick/rmagick: Ruby bindings for ImageMagick - https://github.com/rmagick/rmagick
[2] RMagick 2.12.0: How to use RMagick - https://rmagick.github.io/usage.html
[3] rmagick | RubyGems.org | your community gem host - https://rubygems.org/gems/rmagick
[4] ImageMagick - Image Formats - http://www.imagemagick.org/script/formats.php
[5] imagemagick — Homebrew Formulae - https://formulae.brew.sh/formula/imagemagick
[6] pkg-config — Homebrew Formulae - https://formulae.brew.sh/formula/pkg-config