Some basic batch file examples

I have put together some batch file examples; they all worked for me on a Windows XP machine

Thanks to Fred at Fred's ImageMagick Scripts and Pete at MagickWand Examples in C for their help with these examples.

A link to the new Imagemagick section on Windows use


Some basics

To use a batch file on any image you can use a argument this means you add the file name to the batch file call e.g. watermark image.jpg you can add multiple arguments and you use them in the batch file as %1 %2 etc.

To write one long line of code ( which can happen with Image Magick ) you can end a line with a ^ as long as you start a new line with a space.
convert ^
-resize ^
100x100

Windows needs to escape certain characters and so if you are using % in your Imagemagick code it becomes %% and if you need to use ^ it becomes ^^

You may need to use " in the batch file instead of '

When calling a batch file you can use the name without the .bat extension.

Putting " " around a path SHOULD allow for any spaces in folder and filenames although this did not always work for me.

With some batch files you can drag and drop an image onto the batch file icon and it will modify and save the image.
This is quick as you can have a standard code in a batch file on your desktop, drag an image onto it and it will be modified and saved into a folder designated in the code.

You can call a batch file by double clicking on it but you can not see any errors that may occure and you can not add any arguments

:: Can be used for a comment NOTE:- sometimes you get a strange error and it could be caused by using :: try replacing with REM

echo off - stops the code being displayed during run; add in the @ stops the echo off being displayed as well.

If your code will not work and you think it should try changing the file name as you could have called your file the same name as another bat file or system file.


Resize

This will resize an image that is specified with "resize image.jpg" and save it as th_image.jpg

convert %1 -resize 50x50 th_%1



This will resize an image that is specified with "resize image.jpg output.png" and save it as output.png

convert %1 -resize 50x50 %2



You can pass the image sizes as well "resize input.jpg output.jpg 100 50"
The maximium new image size will be 100 pixels wide x 50 pixels heigh

convert %1 -resize %3x%4 %2


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



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


Add some text to an image

This will add some text to the center of the photo
I saved it as watermark.bat and it is used like "watermark image.jpg"

Watermarked example

:: Set the variable TEXT = The text to add to the image
SET TEXT=Copyright of Anthony

:: Add the text to the image
convert %1 -pointsize 30 -fill black -gravity center ^
-annotate +0+0 "%TEXT%" "%~p1watermarked_%~n1.jpg"


This will add the date the photo was taken to the top left corner of the photo
I saved it as watermark.bat and it is used like "watermark image.jpg"

Watermarked example using some EXIF data

:: Use the ImageMagick identify command to set the variable DateTime
to equal the Date and Time from the photo EXIF data
FOR /F %%x IN ('identify -format "%%[EXIF:DateTime]" %INPUTFILE%') DO SET DateTime=%%x

:: Add the date the photo was taken to the image
convert %1 -pointsize 20 -fill black -gravity northwest ^
-annotate +0+0 "Date: %DateTime%" "%~p1date_%~n1.jpg"


Add the shutter speed and Aperture value to a photo.

Watermarked example using some more EXIF data

Image Magick outputs the aperture value and shutter speed in a format that needs modifying and so the code uses some calculations.

NOTE: adding -ping speeds up the process; on a 3.11MB image it nearly halved the process time.

:: Do not display the code while running
@ECHO OFF

:: Select the F number from the EXIF data and set the FNumber variable
FOR /F %%x IN ('identify -ping -format "%%[EXIF:FNumber]" %1') DO SET FNumber=%%x

:: Set the FNumber1 variable to the F number value
:: Image Magick returns the F number in the format of 700/100 or 40/10
FOR /F %%x IN ('convert xc: -ping -format "%%[fx:%FNumber%]" info:') DO SET FNumber1=%%x

:: Set the value of the shutter variable to the shutter speed
:: Select the shutter speed from the EXIF data
:: Image Magick returns the shutter speed in the format of 810/100
FOR /F %%x IN ('identify -ping -format "%%[EXIF:ShutterSpeedValue]" %1') DO SET shutter=%%x

:: Format the speed to 8.1 and set the speed variable
FOR /F %%x IN ('convert xc: -ping -format "%%[fx:%shutter%]" info:') DO SET speed=%%x

:: Calculate the speed in seconds using the power of 2
:: and save it in the shutterspeed variable
FOR /F %%x IN ('convert xc: -ping -format "%%[fx:floor((pow(2,%speed%)))]" info:') ^
 DO SET shutterspeed=%%x

:: Add the F number and shutter speed to the image
:: and save as exif_OriginalImageName
convert %INPUTFILE% ^
-pointsize 16 -fill black -gravity northwest ^
-annotate +10+5 "Aperture: F%FNumber1% Shutter
speed: 1/%shutterspeed% sec" "%~p1EXIF_%~n1.jpg" 

Modify a whole directory of images

Read a directory and modify all jpg images

::Turn of displaying the code on the screen
@echo off

:: Read all the jpg images from the directory, resize them, add some text and save as a png in a different directory
for %%f in (%1\*.jpg) do ( convert "%%f" -resize 200x200 -pointsize 18 -fill black ^
-gravity northwest -annotate +0+0 "Some text" "%2\%%~nf.png" )

This batch file was named resize.bat and called using "resize path\to\original\ path\to\save"

A similar method using mogrify

::Turn of displaying the code on the screen
@echo off

::Step 1: Create folders if necessary
if not exist "%1\high\nul" md "%1\high"
if not exist "%1\thumb\nul" md "%1\thumb"

::Step 2: Resize all jpg images in folder %1 ( folder in command call )
:: to "high" in subfolder high.
::Save tempory images as miff format to prevent jpg recompression
mogrify -path "%1\high" -format miff -auto-orient -resize 800x600 "%1\*.jpg"

::Step 3: Resize all miff images in folder %1 and save all in subfolder "thumb"
mogrify -path "%1\thumb" -format jpg -resize 100x100 "%1\high\*.miff"

::Step 4: Add watermarked image to the center of the miff image in the high folder.
::Use 25% opacity and save that file as a jpg in subfolder "high"
for %%f in ("%1\high\*.miff") do ^
 ( composite -compose atop -gravity center -dissolve 25,100 -quality 85 C:\xampp\htdocs\boots.png "%%f" "%1\high\%%~nf.jpg" )

::Step 5: Delete all miff files in subfolder "high" as they are not used any more
del /Q "%1\high\*.miff"

:: Call using C:\TEST.bat C:\Users\Anthony\Desktop\TEST 
:: Where the TEST.bat file is in the C folder
:: and C:\Users\Anthony\Desktop\TEST is the location of the images
:: Folder names can not contain spaces

This next example will take a folder of images, create a new folder to save the modified images into ( automaticaly generated ) modify the images - resizing adding text and poleroid effect.
This is a slightly modified code from www.advancedhtml.co.uk
It shows how to use functions; read directories and pass information between functions.

I do have a problem and that is I can not get a negative random number using the batch file. In the end I created the random angle with some Image Magick code.

File saved as poleroid.bat on the F drive and the images are in a folder called Test_images. Usage = "poleroid F:\Test_images"

@echo off

:: Enables local environments to be changed without affecting anything else.
setlocal

:: Stores a directory or network path in memory so it can be returned to at any time.
pushd

:: Jump to skip_functions function
goto :skip_functions

:: Function name makeThumbs
makeThumb

:: Set the variable jpg to the first argument = \generated\
set jpg=%1

:: Remove the .jpg extension
set jpg=%jpg:~0,-4%

:: Add the path to the image in this case " ..\Test_images\image.jpg "
set jpg=..%DIRECTORY%%jpg%

:: Select a random angle
FOR /F %%x IN ('convert null: -format "%%[fx:int(rand()*20-10)]" info:') DO SET ANGLE=%%x

:: Set the IM code for watermarking the image into the variable ANNOTATE
set ANNOTATE=-gravity south -font Arial -pointsize 20 -fill black ^
 -annotate +0+20 "www.rubblewebs.co.uk" -fill white -annotate +2+22 "www.rubblewebs.co.uk"

:: Set the IM code for the poleroid modification into the variable POLOROID
set POLOROID=-bordercolor white -border 6 -bordercolor grey60 -border 1 -background none ^
-rotate %ANGLE% -background black ( +clone -shadow 60x4+4+4 ) +swap -background white -flatten

:: Run the Image magick code
convert %1 ( +clone -resize 600x -auto-orient %ANNOTATE% -compress JPEG -quality 70 -write %jpg%_full.jpg +delete ) ^
 -thumbnail 180x -auto-orient %POLOROID% -compress JPEG -quality 80 -sampling-factor 2x1 %jpg%_th.jpg

:: Goes to the end of the function ?
goto :EOF

:: Function to create the directory to save the modified images into
:skip_functions

:: Select the drive
f:

:: Select the folder
cd %1\images

:: Create the new directory
md %1\generated

:: Variable for use in the thumbs function
SET DIRECTORY=\generated\

:: Call thefunction makethumb for all the images in the folder - added the folder path
for /f %%i in ('dir /b *.jpg') do call :makeThumb %%i %DIRECTORY%

:: Changes to the directory or network path stored by the pushd command.
popd

:: ENDLOCAL - restore the previous settings
endlocal

This next example will resize depending on the original image orentation.

@echo off
Setlocal enabledelayedexpansion

:: Create the output folder if don't exist
MKDIR ".\modified" 2>NUL

:: Set maximium image height
SET /A "newHeight=780"

:: Set portrate extent width
SET /A "portrateWidth=390"

:: Set ratio, for a desired ratio of 0,6, enter 600
SET /A "ratio=600"

    :: Set the variable width to the image width
    For /F %%# in ('identify -verbose -ping -format "%%[fx:w]" "%1"') Do (SET /A "width=%%#")

    :: Set the variable height to the image height
    For /F %%# in ('identify -verbose -ping -format "%%[fx:h]" "%1"') Do (SET /A "height=%%#")

    :: Calculation for ratio
    SET /A "currentRatio=!width!*1000/!height!"

    :: Check if the photo is portrate or landscape and run the relavant code
    ::Condition to meet, 500
    IF !currentRatio! GTR !ratio! (
    :: Only resize if height is over desired ratio
        IF  !height! LSS !newHeight! (
            IMconvert "%1" -verbose -trim ".\modified\%~n1.jpg"
        ) ELSE (
            IMconvert "%1" -verbose -trim -resize x!newHeight! ".\modified\%~n1.jpg"
        )
    ) ELSE (

    :: Only resize if height is over 780
        IF  !height! LSS !newHeight! (
            :: Calculation for portrate extent width
            SET /A "newWidth=!height! * !ratio!/1000"
            IMconvert "%1" -verbose -trim -resize x!height! -background white -gravity center -extent !newWidth!x!height! ".\modified\%~n1.jpg"
        ) ELSE (
            IMconvert "%1" -verbose -trim -resize x!newHeight! -background white -gravity center -extent !portrateWidth!x!newHeight! ".\modified\%~n1.jpg"
        )
    )

PAUSE&EXIT