- Index
Introductions
Windows Image Processing Scripts
Performing Calculations
Beyond the Batch File
Further Information
Most of the commands in IM Examples were written specifically with LINUX and
UNIX shell scripting in mind. Generally as these systems are designed with
batch processing and network servers in mind. However more and more users of
IM want to use it from the Windows Environment. This section provides details
and examples of how you can use IM in that environment and more importantally
how to convert a UNIX shell command (as used in these example pages) to its
Windows DOS equivelent.
I wish to express specific thanks to Wolfgang Hugemann
<ImageMagick@Hugemann.de> who completely re-wrote the original notes
and expanded them to cover a much larger range of topics, of specific concern
to window users. What you see here is his work, and IM users are indebted to
him for his time and patience.
Introduction
Under Windows, simple IM commands are usually run in the Windows Command Shell
(DOS Shell, "
cmd.exe"). For complex operations, performed in a
lengthy command line or in a series of command lines, you will probably better
write a script.
For a series of simple commands, this will most probably be a DOS batch file,
executed in the Windows Command Shell. This approach, however, has its
shortcomings, as the DOS command set is rather limited in comparison to those
of common UNIX command shells.
When running IM under Windows, you basically have the following alternatives:
- Windows command shell (DOS)
- This is run by
cmd.exe (32-bit mode) on Windows NT 4.0,
Windows XP and successive versions and is present on any Windows
computer.
- Cygwin
- A bash-like command shell (www.cygwin.com). When using this shell,
the IM examples presented over here can be run rather exactly as they
appear here. (You still have to rename
convert.exe, see
below.)
- Windows Powershell
- The much more powerful successor of the ancient DOS shell, based on
Microsoft .NET 2.0. It will be shipped with Windows 7 and can be
downloaded for Windows XP and Vista at Microsoft. The Windows Powershell
is run by
powershell.exe.
- Windows Script Host
- The Windows Script Host is based on the .COM technology, present on any
contemporary Windows computer and more akin to a programming language than
a simple script language. The Windows Script Host offers several
programming interfaces. Visual Basic Script (VB Script) and Java Script
are the most common. IM commands can be invoked by using the DOS shell
commands "
Run" or "Exec".
What's the use of a script on my Windows PC?
The following examples basically assume that you run IM on a desktop Windows
computer, possibly attached to a network. Well, there are a lot of readily
available image manipulation programs, such as Adobe Photoshop, Corel's Paint
Shop Pro, IrfanView (
www.irfanview.com)
and even GIMP (
www.gimp.org). So why should
you bother to perform image processing by the command line?
The genuine advantage of using ImageMagick instead of a mouse-driven interface
is that you can completely automate routine manipulations, either for single
files or for a bulk of files. Tasks such as...
- Bulk format conversion
- This is offered by quite a lot of Windows programs, such as IrfanView.
However, IM's versatility when it comes to image formats is unsurpassed.
You can for instance convert all the pages of a PDF into a series of JPEGs
(if GhostScript is installed on your computer).
- Shrinking digital photographs
- When embedding digital photographs into a word processor document, you
should usually reduce their resolution, such that the document can be
printed faster. The same holds if you convert the document into a PDF via
a PDF printer driver such as FreePDFXP.
- Placing your logo into a bulk of digital photographs
- Applying a series of operations to a bulk of digital photographs
- Having worked out a series of working steps by use of a mouse-driven
program, you might wish to automate these steps for future bulk
processing. However, script languages (such as Adobe's Action Script) are
not very common in Windows image processing programs.
- Combining several images to a catalog image
Although some of these tasks (especially bulk-shrinking) is also offered by
freeware programs (especially by IrfanView's batch processing), you are never
free of choice in what processing steps to apply: you have to live with those
offered by the program. For instance, IrfanView's batch processing offers to
place a text string into a photograph, but not a logo. It also offers to
change the gamma value, but the histogram of the photograph cannot be clipped
at its ends (as done by "
-contrast-stretch" in IM, see
Normalize and Contrast Stretch).
IM is especially suited for use in a commercial environment, as ready-made
scripts can be applied by anyone, without actually having an idea about what's
going on in the background.
Windows Image Processing Scripts
Using Batch files under Windows
Let's assume you have a perfect Windows script (a DOS batch file, a
VisualBasic Script, or whatever) that takes the name(s) of the input file(s)
as command line parameter(s), performs some manipulation and spits out the
result as a single image or a series of images. You surely won't like start a
DOS command shell everytime (see below) and provide the script with the
filenames by typing them! To avoid such cumbersome ways of proceeding, you
can basically use
Drag & Drop or
Send To:
When using
Drag & Drop, you place the DOS batch file or the VisualBasic
script (or whatever) in a location that is easily accessible, like the desktop
or the directory which holds the files to be processed. You then select the
files to be processed in the Windows Explorer and just drop them onto the
script. The filenames will be handed over to the script as the command line
parameters and can be referred to in the script.
As an alternative, you can place your script in the
Send To folder. The
programs contained in this folder appear in the context menu of the Windows
Explorer when right clicking in the Explorer's file pane. Again, the names of
the selected files are handed over as command line parameters. The Send To
folder is named "
Sendto". Its location seems to move with each
new Windows version. A bullet-proof way to find it is typing
shell:sendto into the run box.
Converting Scripts: UNIX Shell to Window DOS
When invoking IM commands directly from the DOS command shell
(
cmd.exe) you have to modify the sample scripts presented on this
site (if they don't stem from this very page). The sample scripts are
generally intended to be run in a Linux command shell. In order to run them
from a DOS command shell, you have to perform the following modifications:
- "
convert" is a Windows command in the Windows
system directory (for converting FAT32 to NTFS). It is suggested you
rename the IM convert command to "imconvert.exe" to
distinguish the two commands. You can't rename the system command, as a
windows service pack would just restore it, ignoring the renamed
version.
- Most often, double quotes '
"' have need to be used in place
of single quotes ''' so that the command arguments remain
correct. Watch out for quotes within quotes such as in "-draw" operator. You can use
single quotes within a DOS double quoted argument as these are passed to
IM for handling, and not the DOS scripting language.
- Backslashes '
\' appearing on the end of the shown example
lines represents a 'line continuation' which appends the next line to the
same command line sequence.
Just append all the lines onto one line and remove those backslashes. OR
replace them with '^' character to denote line continuation
in DOS scripts.
- All reserved shell characters which are not in double quotes must be
escaped with a '
^' (caret or circumflex) if used in a literal
sense (i.e. not fulfilling their usual purpose). These reserved shell
characters are: '&', '|', '(',
')', '<', '>',
'^'.
This especially means that:
- The special character '
>' (used for resize geometry)
needs to be escaped using '^'. For example
"-resize 100x100^>"
- Similarly the 'internal fit resize' flag '
^' needs to be
doubled to become '^^'.
- Shell escaping backslashes '
\' are not needed to escape
parenthesis '()' or exclamation marks '!'.
- But escaping backslashes '
\' will need to be replaced with a
circumflex '^' when that escape characters such as
'<' and '>'.
For example: "-resize 100x100\>"
will become "-resize 100x100^>".
- In DOS batch files, the percent '
%' character also has a
special meaning as it references to the command line parameters, i.e.
%1, %2, .... In a DOS batch file, single percent signs (as
they appear in the "FOR command") thus have to be doubled to
'%%'
- Keep in mind that Windows filenames can include space characters.
Such filenames have to be included in double quotes: "file name.jpg" or
"file name".jpg. A filename passed as a command line parameter needs
special attention, as it is passed to the script without bracketing quotes
if it doesn't contain space characters and with double quotes in case that
it does.
- Comments in UNIX Shells start with an unquoted '
#' anywhere
in a line and continue to the end of the line. Color settings (such as
"#FF0000" for a red color) will often be quoted with to remove
this special meaning. This quoting is not needed but using double quotes
'"" around them does not matter and should be kept.
In DOS, comments can only appear at the start of a line using
'REM' (or '@REM') or '::'. They
also continue to the end of the line. It is your choice which method of
commenting you should use. However commenting any batch file is always
recommended, so you know what the command is attempting to do when you go
back to the script years later. Makes it easier for others too.
All scripts should start with a comment explaining what the script does
and how it should be used. This is just good programming practice.
- Unlike a UNIX shell that needs a special command or option to print
(trace) commands as they are executed, in DOS this is the norm. To turn
off this unwanted output start your script with "
@ECHO OFF".
Also the special starting comment "#!/path/to/shell" is not
needed for DOS batch files. So this line can be replaced by the "@ECHO
OFF" command for DOS batch files.
For example, this UNIX shell script...
#!/bin/sh
# Create a negated rose image and overlay a comment
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 batch file...
@ECHO OFF
:: Create a negated rose image and overlay a comment
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
|
I have written a basic Linux shell -> DOS batch file converter by the use of
SED (Streaming EDitor). SED is a common UNIX / Linux text file manipulation
program which is also available for Window at
http://sed.sourceforge.net. Like IM is a
command-driven image manipulator, SED is a command-driven editor. The SED
script 'cim.txt' that performs the needed manipulations looks like this (when
stripped of any comments):
s/convert/IMconvert/ig
s/'/\"/g
s/%/%%/g
s/\\\([()!]\)/\1/g
s/\([&|<>]\)/^\1/g
s/^[ ]*#/::/
s/\(^.*\)\( #.*$\)/\2\n\1/
s/\(.:.*\.[a-z,A-Z]*\)[ ]/\"\1\" /g
s/\\[ ]*$/^/
s/^[ ][ ]//
|
You can download the fully commented version
here.
If you place the SED script 'cim.txt' in the
same folder as the Linux shell script which is to be converted, you invoke the
conversion by:
%programfiles%\GnuWin32\bin\SED -f cim.txt linux.scr > windows.bat
|
You can also invoke the convertion via
Send To or
Drag & Drop by
using the following batch file:
SET SP=%programfiles%\GnuWin32\bin
%SP%\SED -f %SP%\cim.txt "%~1"> "%~dpn1.bat"
|
This batch file assumes that you have placed the SED script 'cim.txt' within
SED's program folder. It takes the filename of the Linux shell script as the
only command line parameter and generates a batch file with the same name, but
extension '.bat' in the same folder. (The crytic filename manipulation
"%~dpn1.bat" is explained in the next section.)
Please note: The above SED script will only perform the rudimentary
replacements mentioned above. It will NOT turn sophisticated Linux shell
scripts (like those presented on Fred Weinhaus' website) into a batch
file!
Windows Filenames Handling
As has been said above, IM is very useful when applying a standard sequence of
processing steps to an image file. In such case, the filename will be handed
to the script as a command line parameter, either via Drag & Drop or via Sent
To. Using these techniques, the filename handed to the DOS batch file will be
a fully qualified filename, include the drive and the directory path. You can
test this be dropping a file onto the following batch file:
Due to the "
PAUSE" statement, the DOS box will stay open until the
user presses a key, such that you can inspect the result. Try the above with a
filename that contains spaces and you will notice that the filename will be
bracketed by double quotes.
When using this filename in "
imconvert", this can cause trouble.
Let us perform a simple conversion from any other format to JPEG. The most
basic code would be:
imconvert %1 %1.jpg
PAUSE
|
This will produce a JPEG file (with standard quality and resolution) in the
same directory, tailed with an additional ".jpg" extension. The above code
works on any filename, whether it contains spaces or not.
If you want to get rid of the original extension, things become a little
trickier:
imconvert %1 "%~dpn1.jpg"
PAUSE
|
The above batch file manipulates the filename by use of the
~
operator:
| %~1
| expands %1 removing any surrounding quotes (")
|
| %~f1 | expands %1 to a fully qualified path name
|
| %~d1 | expands %1 to a drive letter only
|
| %~p1 | expands %1 to a path only
|
| %~n1 | expands %1 to a file name only
|
| %~x1 | expands %1 to a file extension only
|
These modifiers can be combined, such that "
%~dpn1" means "drive +
path + name without extension and bracketing quotes". Consequently, we have to
bracket the name by double quotes, such that the code also works for filenames
including spaces. (If it doesn't, the quotes do no harm.) The
"
PAUSE" statement is for testing purposes only and can be dropped
in the final batch file. If you just want to test your code without actually
invoking IM, you should write:
ECHO imconvert %1 "%~dpn1.jpg"
PAUSE
|
which will just show the result of your string manipulation.
Batch Processing Several Files
The DOS "
FOR" command can be used to process as series of files in
the same manner. In order to scale all JPEG files in the current directory by
50%, you could type the following line into a DOS box:
FOR %a in (*.jpg) DO imconvert %a -resize 50% small_%a
|
Please note that the percent sign is not doubled. If you however place this
command in a batch file you will have to replace it by
FOR %%a in (*.jpg) DO imconvert %%a -resize 50%% small_%%a
|
Again, it is convenient to invoke this bulk operation by Drag & Drop or Send
To, passing a fully qualified filename (or a folder name) to a DOS batch which
is possibly located in another directory (such as
shell:sendto).
In this case, have to make the file's directory the current directory in a
first step:
@ECHO OFF
%~d1
CD %~p1
MD small
FOR %%a in (*.jpg) DO imconvert %%a -resize 50%% small\%%a
PAUSE
|
In this batch file we
- change the drive by supplying the drive name (d: or whatever)
- make the file's folder the current directory
- create a sub-directory named "small"
- scale all JPEG files by 50% and place these shrunken versions in the new
sub-directory.
Section to be reviewed...
 |
 |
 |
One shortcoming of the "FOR" statement is that you can only
perform one single command after "DO". Although the
"imconvert" command can perform rather complex operations in just
one run, problems can arise when intermediate results have to be stored and
force you to use several calls of "imconvert". You can work around
this by calling another batch file
%~d1
CD %~p1
MD small
FOR %%a in (*.jpg) DO CALL "%~dp0process" "%%~fa"
|
Where "process.bat" is the batch file which does the actual work
and which is located in the same directory as the calling batch file. The
command line parameter 0 ("%0") is the name of the batch file
itself, such that "%~dp0process" calls the batch file
"process.bat" in the same directory. The "FOR"
statement provides just the filename, which is turned into a fully qualified
filename via "%~fa".
In case that you don't want to bother with two batch files, you can create
a "process.bat" script within the calling batch file via
"ECHO", and then deleted it when finished.
ECHO imconvert %%1 -blur 30 -negate %%1.miff >%~dp0process.bat
ECHO composite %%1.miff %%1 -compose overlay "%%~dpn1_light"%%~x1 >>%~dp0process.bat
ECHO DEL %%1.miff >>%~dp0process.bat
%~d1
CD %~p1
MD small
FOR %%a in (*.jpg) DO CALL "%~dp0process" "%%~fa"
DEL %~dp0process.bat
|
The batch file created by the first three lines will blur the original image,
invert it and store the intermediate result in a file with an additional
".miff" extension. In the second step, it superposes the original
image over this modified version, thereby lightening darker sections of the
original image. In the third line, the temporary MIFF file is deleted. (In the
last line the temporary batch file shares this fate.)
The two operations performed by the batch file "process.bat"
might possibly be carried out in one run (if you know IM better than me), but
anyway, the above code illustrates the general way of proceeding, that can be
applied to more complex examples. When using the "ECHO" command,
look out that you escape any special DOS characters, especially the percent
sign.
|
You can have multiple commands executed by a "
FOR" by using
parenthesis to group the command within the "FOR" statement.
For Example...
@ECHO OFF
%~d1
CD %~p1
FOR %%a in (*.jpg) DO (
ECHO Processing file: "%%~nxa"
imconvert %%a -blur 30 -negate %%a.miff
composite %%a.miff %%1 -compose overlay "%%~dpn1_light"%%~xa
DEL %%a.miff
)
PAUSE
|
This batch file processes all the images found in the directory given as an
argument. First blurs the original image and negates it, storing the
intermediate result in a file with an additional "
.miff"
extension. Then in a separate command superposes the original image over this
modified version, thereby lightening darker sections of the original image.
Finally the intermediate image is deleted.
I'm not sure about the use of parenthesis as arguments to the
"
imconvert", but I think you can escape them, "
^("
or "
^)", so the "
FOR" comamnd grouping, does not see
them as special any more. Or perhaps they won't be seen as special if they're
inside single quotes.
Yes IM could have done all the above in a single processing command, removing
the need for the "
.miff" intermediate image, but that is not the
point of this example.
The above code has NOT been verified.
Also it is unclear how the above technique would handle parenthesis as
arguments to the "imconvert" command itself.
Please mail me if you can help.
Section to be reviewed...
 |
 |
 |
From this Forum Discussion...
In CMD you can't set a drive and then "CD to a path based on a UNC
filespec, so normal FOR and FOR /R methods don't work. My solution was to
re-invent my UNC tolerant "FOR /F ... IN (`dir...`)" method,
here's some snippets from my latest .cmd:
Only works for non-UNC paths...
:nonUNC
%~d1 & cd "%~pnx1"
for %traverse% %%i in (*.%srcExt%) do set /a ctrDirTotal+=1
for %traverse% %%i in (*.%srcExt%) do ( set /a ctrDir+=1
echo Processing file !ctrDir! of %ctrDirTotal%: "%%~fi"
%%~di & cd "%%~pi" & convert "%%~nxi" "%%~ni.%tgtExt%" && set /a ctrAll+=1
if .%srcDel%==.y del "%%~nxi"
)
|
Works for UNC or non-UNC arguments...
:UNC
for /F "usebackq delims=" %%i in (`dir %slashs% /b %1\*.%srcExt% ^2^>%stdErr%`) do set /a ctrDirTotal+=1
for /F "usebackq delims=" %%i in (`dir %slashs% /b %1\*.%srcExt% ^2^>%stdErr%`) do ( set /a ctrDir+=1
echo Processing file !ctrDir! of %ctrDirTotal%: "%~dpnx1\%%~nxi"
convert "%~dpnx1\%%~nxi" "%~dpnx1\%%~ni.%tgtExt%" && set /a ctrAll+=1
if .%srcDel%==.y del "%~dpnx1\%%~nxi"
)
|
A non-UNC path: "d:\etc..."
A UNC path: "\\hostname\sharename\etc..."
%~d evaluates to "\\"
%~p evaluates to "hostname\sharename\etc..."
Not everyone maps their drives the same, so in a networked environment UNC
paths can be more reliable. Explorer can explore network shares directly and
will pass on UNC style file/folder paths. If the cmd script receives a UNC path
you need to be aware that:
(a) you can't set the current drive to a UNC path, and
(b) since %~p is a relative path you can't CD to that either
FOR works only in the current directory.
FOR /R works down from the current directory or from [[drive:[path]
The FOR /F and `DIR ...` method should work with anything you throw at it ;-)
|
The above code has NOT been verified.
Batch processing a (sub-)directory tree
By using a "
/R" flag with the "
FOR" loop you can
make it loop over all the files in all sub-directories under the current
directory.
For example convert all TIFF format files to JPEG...
FOR /R %%a IN (*.tif) DO imconvert %%a "%%~dna.jpg"
|
Reusing the Output of an IM command
In recent versions of Windows, the "
FOR" command has become much
more powerful, see
DOS "For"
Command Help. By using the "
/F" option, you can read the
input for the substitution variable from a file, a string or from the output
of another DOS command or another program. The latter is especially useful
with IM.
To get a rough idea on what IM's overlay methods really are about, you could
use the following batch file.
imconvert -size 80x80 -flip gradient: compose_src.png
imconvert compose_src.png -rotate -90 compose_dst.png
FOR /F %%A in ('imconvert -list compose') DO ^
composite compose_src.png compose_dst.png -compose %%A compose_%%A.png
|
Src
|
Dst
|
|
Multiply
|
Screen
|
Overlay
|
This script composes two gradient images together, using every possible
Alpha Composition method available, so you can see how
operators effect image colors. Only some of the images it generates are shown
above. This is similar to the images that were generated for
Composition Tables. so you can see how
operators effect image colors.
As this was writing into a batch file, we have to double the percent
signs.
The above script first creates two orthogonal gray-scale images with gradients
covering the entire color range. Then calls the IM command
"
imconvert -list compose" will provide us with a list of possible
options, each placed within a single output line. Please note that we have to
use single quotes when referring to a command in the parenthesis.
Using the "
/F" option, the "
FOR" command will then
process each of these output lines and hand it over to the command executed by
"
DO". As a consequence, the two gradient images are superposed
applying all the overlay methods that IM knows of. The output files are named
according to the overlay method.
In the next example, we illustrate the color spaces which IM provides. We use
the same gradient technique as above to generate the surfaces of a cube as
spanned by the three coordinates of the color space.
imconvert -size 256x256 gradient: gy.miff
imconvert gy.miff -rotate 90 gx.miff
imconvert -size 256x256 xc:black black.miff
::R + G top left
imconvert gy.miff gx.miff -flop black.miff -set colorspace %1 -combine ^
-resize 260x300! -background none -shear 0x-30 ^
-virtual-pixel Transparent RG.miff
:: R + B top right
imconvert gy.miff black.miff gx.miff -set colorspace %1 -combine ^
-resize 260x300! -background none -shear 0x30 RB.miff
:: G + B bottom
imconvert black.miff gx.miff gy.miff -set colorspace %1 -combine ^
-resize 260x300! -background none -shear 0x30 -rotate 120 ^
-crop 520x300+0+75 GB.miff
imconvert -set colorspace %1 RG.miff RB.miff +append top.miff
imconvert -set colorspace %1 -size 520x150 xc:Transparent w.miff
imconvert top.miff w.miff -append topx.miff
composite -geometry +0+299 GB.miff topx.miff colorspace_%1.png
DEL *.miff
|
colorspace RGB
|
colorspace sRGB
|
A similar example to the above using UNIX shell scripting is given in Isometric Cube using Shears.
This batch file takes the color space as a command line parameter
"
%1". It then generates the three sides of the cube and shears
and mounts them such that we get an isometric view, where the point (0,0,0)
lies at the centre of a hexagon. The final picture is named after the color
space (IE. "
%1") and stored as a PNG.
We now want to call this batch file (saved as "
cspace.bat") from
another batch file that provides the names of the color spaces:
FOR /F %%A in ('imconvert -list colorspace') DO CALL cspace %%A
|
We can also filter the output of the
-list option by piping it in
DOS:
imconvert -list colorspace | FIND "RGB" >>clist.txt
FOR /F %%A in (clist.txt) DO CALL cspace %%A
DEL clist.txt
|
In this example, we filter those lines from the output that contain "RGB" and
write them to the file "
clist.txt". This file is than used as the
input for the "
FOR /F" command. We can also do this in one run,
avoiding the temporary file:
FOR /F %%A in ('imconvert -list colorspace ^| FIND "RGB"') DO CALL cspace %%A
|
In this case, the pipe symbol "
|" has to be escaped, because it is
not bracketed by double quotes (only by the single quotes needed for the
"
FOR" statement) and is – at least in command line above
– not meant in is usually sense.
Processing Single Line Output
This technique can also usefully be applied to a single-line output. We can
for example apply an automatised gamma correction that roughly sets the average
brightness of a picture to the middle of the quantum range (i.e. 127 for a
color depth of 8 bit) by a technique explained on
Fred Weinhaus' website:
FOR /F %%a in ('identify -format "%%[fx:log(mean)/log(0.5)]" %1') DO ^
imconvert %1 -gamma %%a "%~dpn1"_c.%~x1
|
This batch file is handed a fully qualified filename as the command line
parameter "
%1", most likely via Drag & Drop or Send To. The
output of the "
identify" command then provides with a gamma
value, which will set the image's average brightness to the middle of its
dynamic range. This value is calculated using a
FX Format Expression. The single line
output of the "
identify" command is saving into the
"
%%a" variable, and passed to the "
imconvert"
command as a argument for the
Gamma Color
Correction.
Please note that the "
FOR" command seems to be quite sensitive
when it comes to line continuations: If you use them at all, make sure that
you better don't start the next line with spaces.
With the same "
FOR" technique, we can read from the EXIF
information embedded in a photograph and write it into the top left corner of
the image:
FOR /F "tokens=1,2" %%i IN ('identify -format "%%[EXIF:DateTime]" %1') DO ^
imconvert %1 -pointsize 18 -fill white -gravity northwest ^
-annotate +0+0 "%%i %%j" "%~dpn1"_dated%~x1
|
  |
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.
|
In the above batch file, the filename of the photo is supplied as the single
command line parameter, which is referred to as "
%1". The
"
identify" command reads the date and time that the photograph was
taken from the EXIF information within the JPEG file. The "
FOR"
command then hands this output over to "
imconvert" which
annotates the photograph accordingly in the upper left corner.
The EXIF date and time information is formatted as "yyyy:mm:dd hh:mm:ss", e.g.
"2006:12:26 00:22:38". Thus date and time are separated by a space character.
By default, the "
FOR" statement would only find the first token
("word") in each line, with tab and space characters as the standard
delimiters. Thus in the example above, the standard processing would only
handle back the date, but not the time. Using the option
"
tokens=1,2" we declare our interest in both tokens, which are
named consecutive, IE. "
%x, %y". We can however change the
rather unconventional formatting of the date by the following code:
FOR /F "tokens=1,2,3,* delims=: " %%i IN ('identify -format "%%[EXIF:DateTime]" %1') DO ^
imconvert %1 -pointsize 18 -fill white -gravity northwest ^
-annotate +0+0 "%%j/%%k/%%i %%l" "%~dpn1"_dated%~x1
|
We now defined the colon ('
:') as an additional delimiter,
causing the date to be broken up into the three tokens "
%i",
"
%j", "
%k". The next delimiter found is the space
character separating date and time. With the asterisk ("*") we asking the
rest of the line to be stored in the fourth token %l. We can now format the
date as we like to. Such as the Anglo-American notation "mm/dd/yyyy" as in the
above example.
Performing Calculations
The DOS command interpreter is poor when it comes to calculations. You can use
it to perform simple integer arithmetics. But for doing more complex floating
point mathematics, you have access to IM's
FX Format Expression, or a third party DOS calculator program.
Using IM's FX Expressions
IM's
FX Format Expression can be used
for floating point mathematics and can add that maths to larger formated
strings, as has been demonstrated above in the first example of the section
Processing Single Line Output. By use of the
"
SET" command, the result can be stored in an environment
variable and used later in the batch file. As a simple example, we may wish to
adjust the font size date-time string in the above example according to the
dimensions of the photograph:
FOR /F %%i IN ('identify -format "%%[fx:min(w,h)*0.05]" %1') DO SET psize=%%i
FOR /F "tokens=1,2,3,* delims=: " %%i IN ('identify -format "%%[EXIF:DateTime]" %1') DO ^
imconvert %1 -pointsize %psize% -fill white -gravity northwest ^
-annotate +0+0 "%%j/%%k/%%i %%l" "%~dpn1"_dated%~x1
|
In the first line we evaluate the smaller dimension of the photograph by
"
%[fx:min(w,h)]", take 5% of this value and store it in the
environment variable "psize". This value is referred to in the next statement
("
%psize%") to set the font size of the time-date
information.
And here we calculate a random angle between as an integer between -15 to +15
to create a rotated thumbnail image.
FOR /F %%x IN ('convert null: -format "%%[fx:int(rand()*31)-15]" info:') DO SET angle=%%x
imconvert %1 -thumbnail x90 -matte ^
-background none -rotate %angle% "%~dpn1"_rotated.png
|
The
FX Expressions can not only
generate numbers, but can also generate multiple numbers, embedded in a larger
string. For example in
Border with
Rounded Corner it was used to directly generate a complex draw string
based on image width and height information.
This added feature, along with avoiding and further dependence on other
external programs makes this method a preferable method for doing calculations
in your batch script.
Using the SET command
The "
SET" command can perform some simple integer math and some
basic string manipulation when the "
/A" option is invoked. In the
following example, we roughly calculate the width of the time-date string by
use of the "
SET" command:
:: Determine the font height
FOR /F %%i IN ('identify -format "%%[fx:min(w,h)*0.05]" %1') DO SET psize=%%i
:: The width of the date-time string is roughly 9 times its height
SET /A pwidth=%psize% * 9
:: Calculate the average brightness in this section
:: and choose the text color accordingly
FOR /F %%i IN ('identify -format "%%[fx:mean]" -crop %pwidth%x%psize%+0+0 %1') DO SET mean=%%i
IF %mean% LEQ 0.5 (SET fcolor=white) ELSE SET fcolor=black
:: Annotate the photograph
FOR /F "tokens=1,2,3,* delims=: " %%i IN ('identify -format "%%[EXIF:DateTime]" %1') DO ^
imconvert %1 -pointsize %psize% -fill %fcolor% -gravity northwest ^
-annotate +0+0 "%%j/%%k/%%i %%l" "%~dpn1"_dated%~x1
|
This sample batch file chooses the color of the date-time string according to
the average brightness ("
%mean%) in the area where it will be
placed: If it is less than 50%, the string will be white, else it will be
black. The example also makes use of the "
IF" statement. Please
note that the "
ELSE" part has to be placed in the same line and
that the first command has to be bracketed.
Using Other External Calculators
As an alternative, you can use a DOS program which provides floating point
math, such as "
EVAL". If you place this file in the IM program directory or in the
Windows system directory, you can perform floating point calculations in any
DOS shell window.
By using the "
EVAL" program, the "
FOR" command and
environment variables, we can make the color cube example from above somewhat
more flexible and its various calculations more transparent:
imconvert -size 256x256 gradient: gy.gif
imconvert gy.gif -rotate 90 gx.gif
imconvert -size 256x256 xc:black black.gif
:: Set the dimension of the color cube / hexagon and calculate the various lengths
SET l1=512
FOR /F %%i IN ('EVAL "round(cos(degree*30)*%l1%)"') DO SET l2=%%i
FOR /F %%i IN ('EVAL "2*%l2%"') DO SET l3=%%i
FOR /F %%i IN ('EVAL "round((1+sin(degree*30))*%l1%/2)"') DO SET l4=%%i
FOR /F %%i IN ('EVAL "round(%l1%/4)"') DO SET l5=%%i
imconvert gy.gif gx.gif -flop black.gif -set colorspace %1 -combine ^
-resize %l2%x%l1%! -background none -shear 0x-30 ^
-virtual-pixel Transparent RG.miff
imconvert gy.gif black.gif gx.gif -set colorspace %1 -combine ^
-resize %l2%x%l1%! -background none -shear 0x30 RB.miff
imconvert black.gif gx.gif gy.gif -set colorspace %1 -combine ^
-resize %l2%x%l1%! -background none -shear 0x30 -rotate 120 ^
-crop %l3%x%l1%+0+%l5% GB.miff
imconvert -set colorspace %1 RG.miff RB.miff +append top.miff
imconvert -set colorspace %1 -size %l3%x%l4% xc:Transparent w.miff
imconvert top.miff w.miff -append topx.miff
composite -geometry +0+%l1% GB.miff topx.miff colorspace_%1.png
DEL *.miff
DEL *.gif
|
Beyond the Batch File
The above examples prove that the simple DOS batch file is astonishingly
versatile when it is combined with the possibilities offered by IM. Yet the
examples also show that doing calculations can turn out to be rather
cumbersome. Summing it up, the features offered by a DOS batch file are still
far below those offered by a real script or even programming language.
Please note that in the examples above, we applied the manipulations either to
a single file or to all files in a directory (tree). Things will become (at
least) very difficult, if we want to pick an abitrary number of files from a
directory and apply some manipulations to them, e.g. combine them in a
definite way. The command line parameters are limited to the number of nine,
IE. %1 to %9.
The DOS batch file language lacks sophisticated control structures, like a
real
IF... THEN... ELSE, control loops, not to speak of
enumerations (
FOR... EACH... IN... DO... END). The access
to (text) files via the
FOR statement is also rudimentary. Such
things are offered by the Windows Script Host, which is another chapter to
treat.
Further Information
Unfortunatally there is no known tutorial (other than this) which specifically
cover using ImageMagick commands in DOS batch files. However the
PC-Ask.com web site
has a useful summary of DOS commands (look in the secion on
"
FOR"), while
DOS "For" Command Help web page has a better explaination of using the
"
FOR" command.
You may also like to look at '
Bonzo'
Batch Script
page.