Monday, December 29, 2008

Resampling images using PowerShell and GraphicsMagick

I needed to resample several images which were scanned at a higher a resolution than expected, so here's a PowerShell script that I created to resample them to a lower resolution using GraphicsMagick. It's probably not the most elegant, but it seems to work for my requirement. Here it is:

$gm = "C:\Program Files\GraphicsMagick-1.3.3-Q8\gm.exe"
$maxResolution = 100
$defaultResolution = "72x72"

foreach ($file in ls *.jpg) {
echo Processing: $file.Name
$resolutionLine = & $gm identify -verbose $file | Select-String -pattern "Resolution:"
echo $resolutionLine
if ($resolutionLine -match "(\d+)x(\d+)") {
if ([int]$matches[1] -gt $maxResolution -and [int]$matches[2] -gt $maxResolution) {
$file.CopyTo($file.FullName + ".bak")
& $gm convert -resample $defaultResolution -units PixelsPerInch $file $file
echo Resampled: $file.Name
}
}
}


To use, copy the code and save it as a *.ps1 file and run it from the directory you wish to resample images, making any edits as needed. (Note: PowerShell and GraphicsMagick must already be installed.) Use at your own risk, I make no guarantees about this script.

Please leave a comment if you find this script helpful or have any suggestions for improvement.

No comments:

Post a Comment