Casting spells with ImageMagick

Image manipulation for users and programmers alike

ImageMagick is a suite of open source tools for creating, editing, and converting bitmap images. The advanced developer can leverage its many capabilities to produce quality, professional bitmap images, and other artwork for display on websites, in marketing brochures, and anywhere the artistic mood may strike. Licensed under the Apache 2.0 license, ImageMagick can be freely used, copied, modified, and distributed in both open and proprietary applications.

Bill Zimmerly , Freelance Writer and Knowledge Engineer, Author

Photo of Bill ZimmerlyBill Zimmerly is a knowledge engineer, a low-level systems programmer with expertise in various versions of UNIX and Microsoft® Windows®, and a free thinker who worships at the altar of Logic. Creating new technologies and writing about them are his passions. He resides in rural Hillsboro, Missouri, where the air is fresh, the views are inspiring, and good wineries are all around. You can reach him at

24 January 2012

Also available in Chinese Russian Japanese

The British science-fiction writer Arthur C. Clarke once observed that, "Any sufficiently advanced technology is indistinguishable from magic." As practitioners using today's advanced technology, it's difficult to argue against how magical our tools sometimes seem. Imagine yourself someone from another time not so long ago, watching how we use modern technology—casting one spell after another as we photograph, transfer, process, and finally print out images of our friends, family, pets, work places, or even ourselves.

ImageMagick is a colorful generic name given to a suite of programs that enable you to create, edit, compose, and convert digital images in more than 100 diverse formats. The tools themselves consist of discrete programs and libraries, allowing your image-manipulating efforts the broadest possible options for accomplishing these tasks, both operationally and programmatically.

This article focuses primarily on using the convert and display command-line utilities. ImageMagick is a deep set of tools, so by the end of this article, you should have a good impression of the suite.

ImageMagick is an editor

Broadly speaking, a computer program called an editor is designed to make it easy for you to create, modify, and save certain types of digital data. There are as many editors as there are specific types of digital data. There are text editors for documents, program code, and scripts, with popular examples being Vi and Emacs. Audio data, editors like Audacity and Wavosaur are available. ImageMagick offers a specialized editor for graphical image editing.

For creating bitmap images

Like many other image editors, ImageMagick offers an interactive image-editing environment. But ImageMagick offers comprehensive programmable application programming interfaces (APIs) for many standard programming languages to use as well. The ImageMagick community of programmers has provided many useful programs for you to choose from to edit into the functionality you're imagining.

When describing the functionality of image manipulation, pictures are better than words, and the ImageMagick website offers a good set of pictures that illustrate what effect each of the image-manipulation functions actually looks like. (See Resources for a link to more information in image manipulation.)

For editing bitmap images

More than a hundred graphical image formats are in common use, so to simplify the process of editing existing images, ImageMagick offers the convert program to not only convert from one format to another but also convert the images to a form that optimizes ImageMagick's own interactive editor.

For incorporating images into projects

Because one of ImageMagick's strengths is its scripting capability, you can write customized scripts to make incorporating images into special projects easy. One example is to have a suite of marketing literature images automatically customized with a perspective client's personal data—name, address, phone numbers, and so on.

To see this capability in action, consider the plain image of my daughter and son-in-law's cat, coincidently named Merlin (Figure 1).

Figure 1. Merlin
Image of Merlin the cat

To label the image with a nice-looking heading, I use a command such as:

$ convert bMerlin.jpg -font Ubuntu-Bold-Italic \
  -pointsize 56 -fill blue -annotate +25+70 \
  'Merlin, the Wizard of Cats' NewMerlin.jpg

Note: If your system does not have the Ubuntu-Bold-Italic font, use with the following command to list the fonts available:

$ convert -list font

After the image has been processed, you get the image shown in Figure 2.

Figure 2. Revised image with the added caption
Image showing the revised image with the added caption

As you can see, casting spells with ImageMagick isn't difficult at all. It just takes practice to get to know how to use the tool. The programmers, er, wizards, who made ImageMagick did a great job of documenting their tool on the website. I encourage you to visit it and enhance what you learn from this article. (See Resources.)

ImageMagick is an image manipulation library

The programmer's library of options with this powerful tool is beyond comprehensive. Using familiar programming languages, you can incorporate ImageMagick's power through simple APIs designed for each language. From simple bash scripting of the raw ImageMagick commands to calling the API functions of languages like C or Perl, the programmability of ImageMagick differentiates it from many other graphical manipulation tools.

You can choose to use the interactive editor to make fine adjustments to one image or across-the-board changes to multiple images. Being able to leverage this suite's diverse editing tools makes it valuable.

Conversions among popular image formats

More than a hundred different graphic file formats exist for digital images. ImageMagick allows you to tame the beast of complexity by being able to work with so many different standards.

ImageMagick is portable among many diverse operating systems. There are functional versions for Windows®, UNIX® and Linux®, Mac OS X, and Apple iOS. This article focuses on the Ubuntu Linux version. To download either the source code or your preferred system's binary version, see the link in Resources.

Binary or source?

As is the case for many open source systems, you face an initial choice when obtaining the program: Do you compile it from the source code or download a binary version already compiled specifically for your system. There are advantages to both methods, but I choose to build the system from source.

Distribution or custom?

Every distribution (or "distro") has its own method for adding pre-built binaries. To install ImageMagick on distros that descend from Debian Linux, as Ubuntu does, you use one of the graphical user interface-based package managers like the Synaptic Package Manager or a command-line operation such as:

$ sudo apt-get install imagemagick

You can also customize ImageMagick to your tastes, such as modifying where it expects its configuration files to be or some unique build setting. To do this, use the command-line option switches when you build ImageMagick from source. You can list these options with the configure command as follows:

$ ./configure --help

Many of these options are useful when you experience trouble building it on your machine.

Building ImageMagick from source

Building most open source programs for *nix-based computers involves three commands, and ImageMagick is no exception. The standard commands are:

$ ./configure
The goal of the configure script is to create a custom Makefile for the next step. It methodically runs a series of steps to determine the configuration of your machine, and then it either reports to you that something critical is missing, like a necessary library, or that everything is fine and the Makefile has been successfully created.
$ make
The Makefile created in the previous step is used by the make program to build all of the programs making up the ImageMagick suite, along with their associated documentation.
$ sudo make install
The final command copies the programs, documentation, and associated data files to their permanent place, where all users of the system will expect them to be found. Usually, this means the /usr/local/bin directory.

Image manipulation for users

ImageMagick is similar to other image editors in that it provides an interactive program in which to edit images. Once invoked, you can access menu-driven image-manipulation tools for editing.

Creating images from scratch

You invoke the interactive ImageMagick editor using the command display with or without an associated file name. The interface is similar to many other drawing-type programs, easy to use, and menu driven.

Enter the command display. You should see the window in Figure 3.

Figure 3. The ImageMagick editor window
Image showing the ImageMagick editor window

Click the window, and then click File > New from the menu to begin creating your bitmap image. You'll be prompted to enter the image geometry, and then the background color for the image. When entering the image geometry, you also have the option of using a gradation for the background colors.

Command-line utilities

The ImageMagick suite contains many command-line utilities. Here's is a brief list:

  • animate. Animates a sequence of images
  • compare. Annotates image differences
  • composite. Creates overlays, putting one image on top of another
  • conjure. Executes scripts written in Magick Scripting Language
  • convert. Converts one image format into another
  • display. The interactive image editor
  • identify. Describes the image file
  • import. Useful for screen or window captures
  • mogrify. Similar to convert
  • montage. Like composite, with multiple images and other effects
  • stream. A scriptable tool for streaming images a row at a time

With your canvas created, you can begin using the drawing tools to decorate it. Click the Image Edit > Draw. The mode changes and you're presented with a new menu and the cursor functionality of the canvas changes. At this point, select a drawing tool and put your ideas to the canvas. You can leave the Draw functionality and Color portions of the image, add special effects, and be creative.

Editing images

You can edit existing images in a variety of ways. Simply entering the command display image-name allows you to use the interactive editor described earlier, but you can use the other tools in the suite to manipulate the image. The convert program, for example, gives you the ability to convert the image file into another common graphic format suitable for different environments.

To see how this is done, we'll use a program to generate a sequence of invitations to a "cat party." This program takes the form of a bash script, so start an xterm and create the first file as follows:

$ touch catcards
$ chmod a+x catcards

Having created the script file and made it executable, your next step is to open your favorite program editor (for example, Vi, Emacs) and enter the bash-scripted program code shown in Listing 1 into the catcards file.

Listing 1. A Bash script for generating invitations
# A "catcard" bash script for demonstrating ImageMagick
# and generating invitations to a "cat party."
# 20111115 by Bill Zimmerly.

# Find the "seq" command, to generate sequence numbers.

SEQ=`which seq`

# Create the guests file. Comment this
# out if "guests" is an external file.
# (Important Note: "cat" in this script
# has nothing to do with cats!)

cat > guests << EOF
Aunt Linda
Uncle Dave
Aunt Rachael
Uncle Joe
Uncle Myk

# Read the guests into an array called "a."
# (Note: IFS is the field separator value,
# which in this case MUST be set for lines.)

a=($(cat guests))

echo "Generating $((${#a[@]})) invitations to:"

# Generate the invitations.

for i in $($SEQ 0 $((${#a[@]} - 1)))
  # Use base=1 for human counting and
  # show it on the console.

  ((j += 1))
  echo $j. ${a[$i]}

  # Prepare the file name.

  echo "Merlin"$j".jpg" > filename

  # Prepare the invitational text.

  echo ${a[$i]}", I love you and"       > text1
  echo "I want you to come to my"       > text2
  echo "cat party to scratch my belly." > text3
  echo "Sincerely,"                     > text4
  echo "Merlin"                         > text5

  # Use ImageMagick's "convert" command
  # to generate a new card.

  convert bMerlin.jpg \
    -font Ubuntu-Bold-Italic \
    -pointsize 24 -fill blue \
    -annotate +25+40 $(cat text1) \
    -annotate +25+70 $(cat text2) \
    -annotate +25+100 $(cat text3) \
    -annotate +25+130 $(cat text4) \
    -annotate +25+160 $(cat text5) \
    $(cat filename)


# Restore the field separator value and clean up
# temporary files.


rm guests
rm filename
rm text1
rm text2
rm text3
rm text4
rm text5

exit 0

Right-click the blank picture of Merlin the cat (Figure 1) and save it to the directory in which the catcards script resides. (The catcards script needs that image file as data.)

Finally, run the script and list the files generated, as shown in Listing 2.

Listing 2. Invoking the script to generate invitations
$ ./catcards
Generating 6 invitations to:
1. Grandma
2. Aunt Linda
3. Uncle Dave
4. Aunt Rachael
5. Uncle Joe
6. Uncle Myk
$ ls Merlin*

Notice that you now have six new images in the directory. Take turns displaying each image with ImageMagick's display command, and notice how they differ from each other:

$ display Merlin1.jpg

For example, Figure 4 shows the image of the invitation generated for Aunt Rachael.

Figure 4. Aunt Rachael's invitation to the cat party
Image showing the version of the image generated for Aunt Rachael's invitation

You can modify this program easily to generate sales literature or customized graphics for all of your clients.

Image manipulation for programmers

Programmers can incorporate image-manipulation functionality in two ways: through the MagickWand API in C or the MagickCore API.

Using the MagickWand API in C

By way of example, the makers of ImageMagick created an example program designed to increase the contrast of Merlin's image (see Resources for a link to more details about this program). Listing 3 shows the code.

Listing 3. A sample C program for changing an image's contrast
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <wand/MagickWand.h>

int main(int argc,char **argv)
#define QuantumScale  ((MagickRealType) 1.0/(MagickRealType) QuantumRange)
#define SigmoidalContrast(x) \
#define ThrowWandException(wand) \
{ \
  char \
    *description; \
  ExceptionType \
    severity; \
  description=MagickGetException(wand,&severity); \
  (void) fprintf(stderr,"%s %s %lu %s\n",GetMagickModule(),description); \
  description=(char *) MagickRelinquishMemory(description); \
  exit(-1); \






  register ssize_t



  if (argc != 3)
      (void) fprintf(stdout,"Usage: %s image sigmoidal-image\n",argv[0]);
    Read an image.
  if (status == MagickFalse)
    Sigmoidal non-linearity contrast control.
  if ((iterator == (PixelIterator *) NULL) ||
      (contrast_iterator == (PixelIterator *) NULL))
  for (y=0; y < (ssize_t) MagickGetImageHeight(image_wand); y++)
    if ((pixels == (PixelWand **) NULL) ||
        (contrast_pixels == (PixelWand **) NULL))
    for (x=0; x < (ssize_t) width; x++)
    (void) PixelSyncIterator(contrast_iterator);
  if (y < (ssize_t) MagickGetImageHeight(image_wand))
    Write the image then destroy it.
  if (status == MagickFalse)

If you've put this source code into a file called contrast.c, you can then use the following command to build the contrast program:

$ cc `MagickWand-config \
     --cflags --cppflags` \
     -O2 -o wand wand.c \
     `MagickWand-config --ldflags --libs`

When the contrast command has been built, you can use it like this to increase the contrast of Merlin's picture:

$ ./contrast bMerlin.jpg MerlinX.jpg

Compare the image in Figure 5 to the images of Merlin above.

Figure 5. Results from running the contrast program
Image showing the results from running the contrast program

The MagickCore API

The low-level interface between the image processing libraries and your programs is the MagickCore API. It is primarily for system programmer use and provides the basic functionality not typically seen at the higher levels: initializing the environment, instantiating objects, Fourier transformation calculations, and so on.

Distributing projects with ImageMagick libraries

ImageMagick is distributed under the Apache 2.0 open source license, which has a few specific requirements should you use it in your projects. Simply put, you must include a full copy of the license with your project distribution and provide clear attribution to The Apache Software Foundation. See Resources for a link to the full details of the Apache 2.0 license.


In the realm of image editors, the ImageMagick suite stands out as a powerful programmer toolkit for the creation and editing of image files. As shown by the previous bash script and C code examples, the toolkit is comprehensive and useful for working magic on your graphics-related projects.



Get products and technologies



developerWorks: Sign in

Required fields are indicated with an asterisk (*).

Need an IBM ID?
Forgot your IBM ID?

Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.


All information submitted is secure.

Dig deeper into Open source on developerWorks

Zone=Open source
ArticleTitle=Casting spells with ImageMagick