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
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 DOS Batch Scripts

Window users should specifically note that...

For example... This command in IM Examples UNIX shell format...

  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 in a Windows DOS script...

  imconvert -background none -fill red -gravity center  ^
          -font "C:\path\to the\font\candice.ttf"  ^
          -size 140x92   caption:"A Rose by any Name"  ^
          ( rose: -negate -resize 200%% ) +swap -composite  ^
          C:\where\to\save\output.gif

Perhaps someone would like to create rough a 'Linux Shell' to 'Window DOS' IM command converter for the DOS users out there.


Thorsten Röllich pointed out that you can use a FOR ... DO sequence in a windows batch script to pass text output of one "convert" command into the arguments of another (known as command substitution). For Example...

  FOR /F "tokens=*" %i IN ('imconvert ...') DO imconvert ... %i ...

Basically the output of the single quoted "imconvert" command in parenthesis is saved into the special batch script "%i" variable and substitued at the "%i" location in the second "imconvert" command. Normally percent characters need to be doubled in window batch scripts, this is the exception.

You can also use it to save the output of "identify" commands. For example here is a dos script that reads the date of a photo, and writes it into the top left corner of the image.

  @ECHO OFF
  :: Set some variables
  SET INPUTFILE=%1

  :: get the date the photo was taken
  FOR /F %%x IN ('identify -format "%%[EXIF:DateTime]" %INPUTFILE%') ^
    DO SET DateTime=%%x

  :: Add the date photo taken to the image
  imconvert %INPUTFILE% -pointsize 18 -fill black -gravity northwest ^
            -annotate +0+0 "Date: %DateTime%" dated_%INPUTFILE%
Photos are typically saved using JPEG format. Reading and re-saving JPEG images causes slight degrading of the image due to JPEG Lossy Compression and as such saving back to JPEG is not recommended.

Note the doubled percent '%' and double quotes '"', within the "identify" command for use in DOS batch scripting, according to the rules above. However I do not claim to understand all the rules concerning the use of percents in DOS scripting, expecially in 'FOR' loops, which seems to also allow some very fancy substitution techniques.

Also remember that IM can be used for floating point mathematics, and can add that maths to larger formated strings. There can be generated and saved into variables to generate more complex "convert" commands later in both DOS and shell scripts. See the first example in FX Expressions which generated the valus of PI, or in Border with Rounded Corner which uses it to directly generate a complex draw string based on image width and height information.


Pete (el_supremo on forum) noted that the DOS percent ('%') variables do have some useful abilities.

This DOS script will do some integer maths to calcule a circle of a given radius.

  @rem Arguments:    radius  imagefile
  @rem Draw a circle of given radius and color on given image

  @rem compute the X coordinate of a point on the circumference of the circle
  set /A rad=320+%1
  set /A colour=255-%1

  imconvert %2 -fill rgb(%colour%,255,127) -draw "circle 320,240 %rad%,240" %2

And this script will resize the single input argument and write it as a png with "resized_" prepended to the name.

  imconvert %1 -resize 50x50 "%~p1resized_%~n1.png"

'%~p1' is just the pathname part of the input '%1' argument.
'%~n1' is just the filename part.
You must put quotes around the output filename because if it contains spaces (e.g. "C:\Program Files\test.jpg") then DOS will parse it as two (or more) separate arguments.

Unfortunatally there is no known tutorial which specifically cover using ImageMagick commands in DOS batch files but the PC-Ask.com web site has a useful summary of DOS commands. The '%~p1' sort of syntax is covered under the 'FOR' command.

You may also like to look at 'Bonzo' Batch Script page.


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...

<?html
  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/html5extras/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...

<?html
  $im_path="/opt/html5extras/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.

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...

<?html
  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...

<?html
  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...

<?html
  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 PECL 'IMagick'

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.

<?html
  $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 );
?>

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...

<?html
  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...

<?html
  $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.


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 15 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. You should be able to do all your processing in one single step.

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. Often later in the same example area I repeat the process but using a single command. 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 another 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 a separate command 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 can a MPC file can speed up the reading of intermediate files to a near instant in the next processing step.

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.

Create a working temporary directory in which to build IM

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

Now build the RPMs... All the defines in the command restrict the build to just the top level of the temporary directory. If you remove all the defines the RPMs will be built in the system /usr/src area which is usually root owned though does not actually have to be.

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

Get the just built RPMs for the magick core and PerlMagick, you may like to grab more than just two core RPMs, but that is up to you...

  cp -p $rpmdir/RPMS/*/ImageMagick-[6p]*.i386.rpm

Clean up the build areas...

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

Now you can install the RPM packages you build specifically for your linux system... You will need to be root for this, and only this, step...

  rpm -ihv --force --nodeps  ImageMagick-*.i386.rpm

To upgrade an existing installation I generally do this due to some unusal dependancies that sometimes exists on Linux systems...

  rpm -Uhv --force --nodeps  ImageMagick-*.i386.rpm

To later remove IM, do this (again as root)...

  rpm -e --force --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 gurantees about this, and I would check the commands throughly before hand to ensure they don't remove something that it shouldn't. If I 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/{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*

Warning, other packages may need an IM installed, so if you remove it, I suggest that you immediatally update your computer system, so as to install the default version supplied by your linux system. This generally involves using a 'GUI Software Update" package or "yum".

Enjoy.


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

a