ImageMagick v6 Examples --
API & Scripting

Index
ImageMagick Examples Preface and Index
API and other IM usage methods
Security Issues
Hints for Better ImageMagick Shell/PHP Scripts
Why do you use multiple "convert" commands
Making IM faster (in general)
Creating linux RPMs from SRPMs
ImageMagick from Source on Ubuntu
Creating a Personal ImageMagick Installtion
The Command Line Interface (CLI) of ImageMgaick which this examples deals with is only one method by which you can use, modify and control images with the core library of ImageMagick functions (MagickCore). It is basically the 'shell' API interface. There are lots of other Application Programming Interfaces (API's) which you can use more directly from many programming languages, see ImageMagick APIs.

Here I look at ways of improving your IM scripting and programming, differences between Windows and Unix scripting, and look at basics of using IM from other API's and programming languages.


APIs and other IM usage methods

Windows, and DOS

The examples on using Windows and DOS scripting, has been moved to its own section, under the top level.

PHP (IM commands from "system()" functions)

PHP users have three ways of using ImageMagick, The "imagick PECL interface, the "MagicWand" interface, and the much more common method of useing "system()" to run "convert" as a shell command. As IM Examples is mostly about using the command line, that is the form I will look at here.

PHP using Shell Commands

The best source of information on using this technique is the IM forum user Bonzo and his web site RubbleWebs.

The following is the recommend procedure for initial tests of an ISP command line IM interface, assuming you do not have direct command line 'shell' access on the remote system. That is you can only upload web files for execution.

So the first thing we need to do is try and find and run the 'convert' command. to get information about the PHP web server you are using.

On a Linux Web Service Provider upload and access this PHP script from the ISP's web server...

<?php
  header('Content-Type: text/plain');
  system("exec 2>&1; type convert");
  system("exec 2>&1; locate */convert");
  system("exec 2>&1; convert -version");
  system("exec 2>&1; convert -list type"); <!-- before IM v6.3.5-7 -->
  system("exec 2>&1; convert -list font");
?>

This will a number of commands to see what is present. The first "type" command tells you if "convert" is available on the command PATH, and if so where is it. The "locate" command should find all convert commands that exists on the server, including those that are NOT a ImageMagick "convert" command. You will need to interpret the results.

The next three commands, assume "convert" is on the command PATH, and asks it to report its version number, and what font does IM thing it has access to.

If you only see errors, then the "convert" is not on the command line path, and your ISP provider did NOT initialise the web server PATH properly to include it.

If this is the case you will need to find out exactly where it is located and use something like this for you PHP scripts, which makes your script less portable.

For example supose the "convert" command is in "/opt/php5extras/ImageMagick/bin", then you can set that in a variable at the top (for quick changes for different ISP hosts), and directly specify its location...

<?php
  $im_path="/opt/php5extras/ImageMagick/bin"
  header('Content-Type: text/plain');
  system("exec 2>&1; $im_path/convert -version");
  system("exec 2>&1; $im_path/convert -list type");
  system("exec 2>&1; $im_path/convert -list font");
?>

If you get "ldd" library errors, the LD_LIBRARY_PATH is wrong, and the ISP has definitely fallen down on the job during its installation, and you need to report the error, and have them fix the web servers LD_LIBRARY_PATH environment variable setting.

Rather than set the location of the convert command, you can also adjust the PATH environment variable with a line such as this at the top...

  putenv("PATH=" . $_ENV["PATH"] . ":/opt/php5extras/ImageMagick/bin");

After that try some of the simpler examples from IM Examples and try to get them working. EG: For example output the IM 'rose' image as a JPEG image file back to the web user...

<?php
  header( 'Content-Type: image/jpeg' );
  system("convert rose:  jpg:-");
?>

Or try one of the fonts listed from your PHP test scripts. On my Solaris Server I noticed that the 'Utopia' font set was available so I was able to try to create a label with that font...

<?php
  header('Content-Type: image/gif');
  system("convert -pointsize 72 -font Utopia-Italic label:'Font Test' gif:-");
?>

Watch the extra quotes Note that typically the IM commands in PHP are wrapped by an extra set of quotes (usually double quotes), as such care must be taken to allow for the use of these extra level of quoting. For example, this command...

  convert -background none -fill red -gravity center \
          -font Candice -size 140x92 caption:"A Rose by any Name" \
          \( rose: -negate -resize 200% \) +swap -composite    output.gif

Will become something like this PHP equivalent...

<?php
  header('Content-Type: image/gif');

  $color="red";
  $image="rose:";
  $scale="200%";
  $size="140x96";
  $string="A Rose by any Name";

  passthru("convert -background none -fill '$color' -gravity center" .
            " -font Candice -size '$size' caption:'$string'" .
            " \\( '$image' -negate -resize '$scale' \\) +swap -composite" .
            " gif:-" );
?>

Note how I still split up the lines to make the image processing sequence easier to follow, by using appended strings rather than a shell line continuation.

Also note the extra space at the start of later lines. And doubling up the other backslashes that was present in the original command. Alternatively you can protect those options by using single quotes instead of backslashes.

I also used some PHP variables to allow easier adjusted of the PHP script image generated, as well as to control the results, but insert those options using single quotes to protect them from further modification by the shell. Watchout for single quotes within those inserted strings.

You could make those options PHP arguments, so you can generate an image for any input text, however I would be careful to throughly check ALL the PHP input for correctness, and prevent anything unexpected. Otherwise it is very easy to create a 'hole' in the web servers security.

You can perform multiple shell commands within the same system call string. In fact a single system call can contain a complete shell script if you want! So you can do shell loops and multiple commands (with cleanups) all in the one system call. Something not may people realise.

Basically if you are careful, you can make good use of the mathematics provided by PHP, and the scripting abilities of the shell. All at the same time. Just watch the quotes.

I recomend you at least read the PHP manuals on PHP exec(), system(), and passthru() and understand there differences between them.

For various examples of calling ImageMagick commands from PHP see Rubble Web, Writing IM code in PHP which describes about four different techniques.

The more secure method...

Also if you what to avoid the shell parsing the arguments and the need for most of the quoting requirements, (you separate the arguments yourself), such as for security reasions, or specific user input, then use the pcntl_exec() PHP function. This basically avoids all the quoting or other shell escaping, and is thus much more secure that using a 'all in one string' type command. Note you will also

However you will also have to fork a sub-process for the funtion to run in as well, ir it replaces the PHP being executed. This can thus get fairly complex. It is just a shame that PHP has not provided a simple 'shell-less' command execution function, such as those provided in other languages like perl.

PHP 'IMagick' API

To test if the PHP PECL Imagick module is actually working upload a simple test "image.jpg" image and this PHP script to the same web assessable directory.

<?php
  $handle = imagick_readimage( getcwd() . "image.jpg" );
  if ( imagick_iserror( $handle ) ) {
    $reason      = imagick_failedreason( $handle ) ;
    $description = imagick_faileddescription( $handle ) ;

    print "Handle Read failed!<BR>\n";
    print "Reason: $reason<BR>\n";
    print "Description: $description<BR>\n";
    exit ;
  }
  header( "Content-type: " . imagick_getmimetype( $handle ) );
  print imagick_image2blob( $handle );
?>

More examples of using IMagick can be found in Mikko's Blog.

PHP 'MagickWand'

You can check if the PHP MagickWand module is part of the PHP installation (and switch to command line or other fallbacks) using...

<?php
  if (extension_loaded('magickwand')) {
    echo "PHP MagickWand is available!";
  }
?>

But to check that it is actually working properly, upload some test "image.png" and this script...

<?php
  $image = NewMagickWand();
  if( MagickReadImage( $image, 'image.png' ) ) {
    header( 'Content-Type: image/jpeg' );
    MagickSetImageFormat( $image, 'JPEG' );
    MagickEchoImageBlob( $image );
  } else {
    echo "Error in MagickReadImage()";
    echo MagickGetExceptionString($image);
  }
?>

No guarantees with the above, though more feedback welcome. I do not generally program in PHP, but used the above for testing a SunONE-PHP5 test installation (with all three methods: command-line, magick, MagickWand).

Complex PHP scripts...

If you need to generate and output both HTML and IMAGES, consider designing your PHP script so that separate HTML requests or input options, generate the various parts you need on your web document, from either the same, or different PHP scripts.

That is a top level PHP script can output HTML with appropriate <IMG> tags, that call itself (or another PHP script) with appropriate options, to create or modify the images displayed on the first top level PHP script. This is in what a lot of photo album, and graphing PHP scripts do. All controlled by the GET, and PATH_INFO extensions to the URL calls. Note that you can not use POST within an IMG tag.

By doing things in this way you should be able to completely avoid the need to both generate, save, and clean-up, temporary images for PHP generated web pages. A solution that is full of problems, such as resource limitations and garbage collection, making it a very bad programming technique.

Perl Magick Scripts

The PerlMagick API is a good way of conveting "convert" commands into a script that can also handle databases, large numbers of images, or more complex image processing, that is otherwise posible. The best help is to look at the PerlMagick 'demo' scripts, which is both in the source, and usually installed in the documentation area of PerlMagick. On my system that was in "/usr/share/doc/ImageMagick-perl-*/demo/". In this directly are a growing number of simple examples of reading, writing and processing various images. Also present is the script "demo.pl" that lists just about all common Image Processing options, and how you can use them.

When converting a command line "convert" command to perl there are a few things you need to remember.

To convert a command line into perl, you would basically do the exact same operations, in the exact same sequence. However as images are generally not deleted, and multiple image sequences are common, the use of parenthesis, and extra cloning operations in "convert" commands are usally not a issue.

The hardest part in converting scripts is usually mapping a command line option to a PerlMagick function call. The fastest way I found is to get the source code of IM and look at the file "wand/mogrify.c" and search for the specific command line option you are having trouble with.

For example for say the -threshold option search for "threshold" including the quotes. Their will be two matches, one for a quick syntax parse to make sure all the options are found, and the second with the actual internal calls for that option. Here you will find the name of the library function used, and that will usally directly map to the Perl function. In this case... BilevelImageChannel()


Security Warnings

When writing a script for public use, especially a web-based PHP script where ANYONE in the world could be running it, it is vitally important to check everything that could posibly have come from a unknown (or even a known) user. And I mean EVERYTHING, from arguments, filenames, URLs, and images too.

Until you verify some input argument, that argument it could contains letters, numbers, spaces, punctuation, or even 'null' and control characters. Untill you have throughly checked it, it should be treated as suspect and should not be used.

It does not matter that you are using some web controlled input form. A slightly knowledgeable person can easily call your PHP with his own arguments without using that input form at all. An don't believe they won't do it, robots are out there, reading input forms and creating there own 'hacked' arguments to try an break into random scripts.

Meta-characters in file names

As a security issue, you should especially watch out for, are filenames that contain spaces, quotes, punctuation, control-characters, or other meta-characters as both IM and Shells may try to expand them.

The problem is that a file called '*?@${&) .jpg' is actually a perfectly legal filename under UNIX, but a LOT of programs will have trouble handling it if that program (like shell and IM) also do filename expansion. Even when you quote the file name correctly some filenames can still break your quoting, and IM itself does some filename expandsion.

As a security measure it is often a good idea to error and abort if a filename has some unknown or unusual characters in it, anything that is say not a letters, numbers, and the expected suffix. Before passing such a filename to a shell command, or IM. It is better to be a LOT to restrictive and prevent things, than be permissive and allowing something bad through.


Hints for Better ImageMagick Shell/PHP Scripts

These were some basic script programming points I made about a contributed shell script that was sent to the IM mail list for others to use. I originally sent these to the author privately (and who will remain anonymous), for which he was grateful. They are not all IM specific, but should be applied anyway, as standard programming practice. Especially if you plan to have someone else, use, look at, and/or bug fix your program or script. It will in turn make your script more useful.

These things basically gives the user using your program more freedom to do what THEY want rather than what YOU want. Don't limit them or yourself by making assumptions on what the script will be used for.

PS: One of my main expertise is in UNIX script writing, over lots of different architectures and 'flavors' of UNIX, LINUX, and other UNIX-like systems, with more than 25 years experience behind me. I should know what I am talking about with regard to the above.


Why do you use multiple "convert" commands

Willem on Wed, 25 Oct 2006 wrote...
I was wondering; sometimes I see in your examples you're invoking Convert more then once to obtain the desired result. In general, I would expect that invoking convert more then once isn't needed; it should all be possible in 1 invocation (but the command would be more complex then). Do you agree with this statement?

I agree totally. Though before IM version 6 that was actually imposible, as it was never really designed to do more than a couple of operations per command. However IM v6 should allow you to do all your processing in one single command.

I use multiple commands for a number possible reasons. Typically in the example pages, I do it so I can get and display the intermediate image result, so as to better demonstrate the intermediate processing stages that are involved. Later in the same example area I may repeat the process but using a single command, with perhaps a little more complexity. As such in principle, yes a single command can do all image processing.

The exception to this is in cases where I need to extract information and later insert that info into the next command. An example of this is the Fuzzy Trim technique which requires you to extract the results of a trim on a blurred copy of the image. This result is then used to crop the original image. I also did this in the update to Thumbnail Rounded Corners example, where I used IM itself to generate a draw command using an images size for the next command.

However there is a proposal that will allow options to be generated from image that have been previously read into memory.

You are most welcome to combine the image processing techniques all into a single command. I do this all the time myself.

In scripts, such as the 'jigsaw' script (see Advanced Techniques, Jigsaw Pieces) I commonly end up using multiple commands for a different reason -- optional processing. This allows various input options provided by the user to select additional steps in the image processing sequence. So for optional processing I also use typically use separate commands for each stage of processing.

In such a case a temporary file is basically unavoidable. However I typically only need at most one or two temporary images, and each step processes the image back into the same temporary filename, for the next optional processing step to continue with.

EG: convert /tmp/image1.png ..operations.. /tmp/image1.png

In this case a MPC file can speed up the reading of intermediate files to a near instant in the next processing step, as the image is simply dumpped from memory onto disk, and then 'paged' back in by the next command. This avoids the need for IM to format and parse a image file format, though it does make the temporary file larger as it is simply uncompressed memory.

And finally you may need to change your processing style based on the results of previous processing steps.

For example in image comparisons, I often need to change techniques based on the type of images being compared. Comparing a diagram or cartoon can require vary different techniques to say a photo image.

If multiple commands is becoming a problem, perhaps it is time to go to an API interface such as PerlMagick, where multiple image sequences can all be held in memory so as to avoid unnecessary disk IO.


Making IM Faster (in general)

There are many ways of making IM work faster. Here are the most important aspects to keep in mind. As you go down the list the speed up becomes smaller, or requires more complex changes to the IM installation.


Building ImageMagick RPMs for linux from SRPMs

You do NOT need root to actually build the RPM's though you do need root to install the RPMs.

I use this for generating and installing IM under Fedora Linux Systems, but it has also been reported to work for CentOS 5.2 (Enterprise Redhat) Linux Systems. If you have had success or failes on other system, or know how to generate a DEB package version, then please let me know, so I can include it here.


First get the latest source RPM release from Linux Source RPMs.

First make sure your machine has all the compilers and tools it needs.

  sudo yum groupinstall "Development Tools"
  sudo yum install rpmdevtool libtool-ltdl-devel

The "sudo" is a program to run commands as root, if you are allowed, otherwise use a root shell and remove the "sudo" part from the above.

You should also ensure that the these packages and their dependancies (such as jpeg and png development libraries) are also installed:
freetype-devel ghostscript-devel libwmf-devel jasper-devel lcms-devel bzip2-devel librsvg2 librsvg2-devel liblpr-1 liblqr-1-devel libtool-ltdl-devel .
Some examples in "ImageMagick examples" also may use programs provided by these optional packages and libraries
gnuplot autotrace autotrace-devel .

They are in general optional, but if not installed, then parts of IM that make use of those libraries may not be built in automatically. For example the "liblqr" module is needed to enable the Liquid Rescale Operator.

Now download a SRPM (source RPM) package from whcih to build your binary RPMs.

OR build a SRPM from an existing TAR or SVN download using...

  rm config.status config.log
  nice ./configure
  rm *.src.rpm
  make srpm

No that you have the SRPM you can build the RPM's to install. But first we need to create a working temporary directory which is writable by you, in which to build the ImageMagick RPM packages.

  rpmdir=/tmp/imagemagick-rpmbuild
  rm -rf $rpmdir; mkdir $rpmdir
  mkdir $rpmdir/{BUILD,RPMS,SOURCES,SPECS,SRPMS}

Now build the RPMs in that directory...

  nice rpmbuild --define="_topdir $rpmdir" \
      --nodeps --rebuild   ImageMagick*.src.rpm

The defines in the command restrict the build to the defined directory just created. One that you as a non-root user can write to. If you remove them the RPMs will be built in the system "/usr/src" area which is usually root owned. The newer linux machines however will automatically create a non-root RPM build in a "rpmbuild" sub-directory of your home. Only experience will tell you what your particular machine will do.

Now get the just built RPMs from build directory. This only grabs the ImageMagick Core and PerlMagick packages, you may like to grab more than just these two, but that is up to you...

  cp -p $rpmdir/RPMS/*/ImageMagick-[6p]*.i[36]86.rpm .

Clean up and delete the build areas (including those that may have been created for you)...

  rm -rf $rpmdir  /var/tmp/rpm-tmp.*  ~/rpmbuild

Now you can install the RPM packages you built. You will need to be root for this, (see note about the "sudo" command above)...

  sudo rpm -ihv --force --nodeps  ImageMagick-*.i[36]86.rpm

The "--nodeps" is typically needed due to some unusal dependancies that sometimes exists on Linux systems.

To upgrade an existing installation I generally do this (as root).

  sudo rpm -Uhv --force --nodeps  ImageMagick-*.i[36]86.rpm

If you want to go further I recomend you look at the Advanced Unix Source Installation Guide from the IM web site.


To later remove IM, you can just remove the package, like this (again as root)...

  sudo rpm -e --nodeps  ImageMagick\*


Sometimes I just want to completely clean and wipe out all traces of IM from the system. To do this I first use the previous command to remove the actual package from the system (a variation is shown below). I then run the following remove commands.

NOTE I make no guarantees about this, and I would check the commands throughly before hand to ensure they don't remove something that it shouldn't. If it missed anything, or it removed something it shouldn't, then please let me know so I can update it.

  rpm -e --nodeps `rpm -q ImageMagick ImageMagick-perl`
  rm -rf /usr/lib/ImageMagick-*
  rm -rf /usr/lib/lib{Magick,Wand}*
  rm -rf /usr/share/ImageMagick-*
  rm -rf /usr/share/doc/ImageMagick-*
  rm -rf /usr/include/{ImageMagick,Magick++,magick,wand}
  rm -rf /usr/lib/perl5/site_perl/*/i386-linux-thread-multi/Image/Magick*
  rm -rf /usr/lib/perl5/site_perl/*/i386-linux-thread-multi/auto/Image/Magick*
  rm -rf /usr/share/man/man?/*Magick*
  rm -f /usr/lib/pkgconfig/ImageMagick.pc

Warning, other packages may need an IM installed, so if you remove it, I suggest that you immediatally package update your computer system, so it will again install the original default (and usally quite old) version of ImageMagick that was supplied for your linux system. This generally involves using a 'GUI Software Update" package or the command "yum upgrade".

Enjoy.


ImageMagick from Source on Ubuntu

A web page by "Shane" describes how to Install ImageMagick from Source on Ubuntu 8.04.

I have not tried this, but this installed IM into "/usr/local" directly using "make". It does not generate a installation 'DEB' package, which would be the ideal solution.

If anyone know how to create a 'DEB' package for Ubuntu, please let me know.


Creating a Personal ImageMagick

You do not always have the luxury of having superuser access to the machine on which you are doing image work on, and often those that do have that access do not want to update their ImageMagick installation. prehaps for package management issues, or compatibility problems.

If you have command line access (for example via SSH) all in not lost. You can install and use a personal version of ImageMagick.

The bad news is you will still need the system administrators to install the compilers and development packages (see above), but often these will already be present, so is not always a problem. First decide in what sub-directory you want to install your version of IM. A dedicated directly is the best choise as it mean you only have to delete that whole directory to remove your installation. In my case I'll install into the "apps/im" sub-directory of my home.

  export MAGICK_HOME=$HOME/apps/im

Now to install a personal version, download, unpack, and change directory into the ImageMagick Sources. Then configure it as a 'uninstalled' version.

  rm config.status config.log
  nice ./configure --prefix=$MAGICK_HOME --disable-installed \
          --enable-shared --disable-static --without-modules --with-x \
          --without-perl --without-magick-plus-plus --disable-openmp \
          --with-wmf --with-gslib --with-rsvg --with-xml \
          CFLAGS=-Wextra \
          ;
  nice make clean
  nice make
  nice make install

Now to use your installed version, instead of the normal system version you only need to set the following environment variables.

  export MAGICK_HOME=$HOME/apps/im
  export PATH="$MAGICK_HOME/bin:$PATH"
  export LD_LIBRARY_PATH="$MAGICK_HOME/lib:$LD_LIBRARY_PATH"

Now if I type

  convert -version

I can see that I am the just installed, more up-to-date version of IM by default.

Note that the variable "$MAGICK_HOME" is required for a Imagemagick created with a "--disable-installed" option. The other two variables specify to use the executables and libraries (respectively) for your version before that of the system version.

That is it, a up-to-date personal installation of IM, just for you.


WARNING: do not mix the above variables. Either define all of them or do not have them defined in this way. The IM executable you use MUST also use the same libraries, coders, and configuation files that were built with those executables. Mixing the system and your personal version will likely cause segmentation and memory faults.


You can rename or move the location of your personal IM, but you will need to not only modify the above variables, but also change or remove the hardcoded paths to the "display" program used by the "show:" delegate in your personal installed version of the "delegate.xml" file. See Delegates for more information on this aspect of IM.


To make the switching between multiple personal versions or the system version, I typically create a script, and by default do not set the above variables, allowing the script to set them just for the time they are needed.

For example I have a personal version of IM that was compiled with HDRI quality, which I use for testing purposes. However I don't normally want to use this version, prefering the non-HDRI system version instead.

As such I created a script called "hdri" containing...

#!/bin/sh
#
#   hdri imagemagick_command....
#
# Run the HDRI version of imagemagick (or other personal installed IM)
#
# Where is the HDRI version of IM stored
export MAGICK_HOME=$HOME/apps/im_hdri

# Set the other two environemtn variables
export PATH="$MAGICK_HOME/bin:$PATH"
export LD_LIBRARY_PATH="$MAGICK_HOME/lib:$LD_LIBRARY_PATH"

# Execute the HDRI version of the command
exec "$@"

Now if I type...

  hdri convert -version

I can run my HDRI quality version of ImageMagick, but only when I need it. If I don't prefix "hdri" to the above, I then use the normal system version of IM.

WARNING: If your personal version of IM is not found by the script, it will silently revert to using the system version. The above 'version' check is an important test to make sure that I am actually using my personal version, and not the system version.


Created: 26 October 2006
Updated: 14 September 2009
Author: Anthony Thyssen, <A.Thyssen_AT_griffith.edu.au>
Examples Generated with: [version image]
URL: http://www.imagemagick.org/Usage/api/