Recursive, Batch Image Conversion with PowerShell and ImageMagick
Wednesday, January 11, 2012 at 2:05PM
saveenr

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
}
  
Article originally appeared on viziblr (http://viziblr.com/).
See website for complete article licensing information.