« The Open Sans Typeface – Cool, Sublime and Free | Main | Automatic Rotoscoping with AutoScope »
Wednesday
Jan112012

Recursive, Batch Image Conversion with PowerShell and ImageMagick

All 5 readers of this blog may recall my recent explorations into image formats: [1] , [2], [3], [4]. In the middle of all this, I needed to perform some batch conversion from my original screenshots into other formats or into the same format but using a different encoder.

Below is the PowerShell script I've been using. It's pretty simple. It takes one folder of images and mirrors that folder recursively with the converted format.

# ----------------------------------------
# Configuration
$srcfolder = "D:\Screenshot-Analysis\ScreenShots-PNG-Original"
$destfolder = "D:\Screenshot-Analysis\ScreenShots-WEBP-Lossless2"
$im_convert_exe = "D:\Screenshot-Analysis\ImageMagick-6.7.4-4\convert.exe"
$src_filter = "*.png"
$dest_ext = "jpeg"
$options = "-quality 90"
$logfile = "D:\convert_data.txt"
# ----------------------------------------

$fp = New-Item -ItemType file $logfile -force
$count=0
foreach ($srcitem in $(Get-ChildItem $srcfolder -include $src_filter -recurse))
{
    $srcname = $srcitem.fullname

    # Construct the filename and filepath for the output
    $partial = $srcitem.FullName.Substring( $srcfolder.Length )
    $destname = $destfolder + $partial
    $destname= [System.IO.Path]::ChangeExtension( $destname , $dest_ext )
    $destpath = [System.IO.Path]::GetDirectoryName( $destname )

    # Create the destination path if it does not exist
    if (-not (test-path $destpath))
    {
        New-Item $destpath -type directory | Out-Null
    }

    # Perform the conversion by calling an external tool
    $cmdline =  $im_convert_exe + " `"" + $srcname  + "`"" + $options + " `"" + $destname + "`" " 
    #echo $cmdline
    invoke-expression -command $cmdline

    # Get information about the output file    
    $destitem = Get-item $destname

    # Show and record information comparing the input and output files
    $info = [string]::Format( "{0} `t {1} `t {2} `t {3} `t {4} `t {5}", $count, 
	$partial, $srcname, $destname, $srcitem.Length ,  $destitem.Length)
    echo $info
    Add-Content $fp $info

    $count=$count+1
}
  

PrintView Printer Friendly Version

EmailEmail Article to Friend

Reader Comments (2)

Thanks a lot. You saved me so much time.

Since I have spaces in the path to ImageMagick, the only thing I had to modify has been:
$cmdline = " `"" + $im_convert_exe + "`" " + ...
invoke-expression -command "& $cmdline"

May 28, 2012 | Unregistered CommenterPeffy

Thanks. Just what I was looking for!

April 23, 2014 | Unregistered CommenterAsh

PostPost a New Comment

Enter your information below to add a new comment.
Author Email (optional):
Author URL (optional):
Post:
 
Some HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>