Thursday, December 27, 2007

Bulk image conversion in PowerShell

 

I used to converted large amounts of images from one format to another in Adobe® Photoshop®. Photoshop has an amazing set of tools to bulk convert images and apply different filters/actions on the images. It even offers a COM scripting engine for VBScript and JScript (and AppleScript).

Did you know that you can do it in PowerShell? Well, PowerShell doesn't offer all that Photoshop has, but for a task as image/bulk conversion, PowerShell definitely gives you what you need, fast and simple.

For a complete list of conversion-able formats see the ImageFormat Class.

 

Get all BMP files from the Windows directory, convert them to JPEG files and store them in the C:\Temp directory:

[void][reflection.assembly]::LoadWithPartialName("System.Windows.Forms")
$imgDir = "c:\temp"

get-childitem $env:windir -filter *.bmp | foreach {
    $baseName = [System.IO.Path]::GetFileNameWithoutExtension($_.fullname)
    $img = new-object system.drawing.bitmap $_.fullname
    $img.save("$imgDir\$baseName.jpeg",[System.Drawing.Imaging.ImageFormat]::Jpeg)
}

 

img

 

# build a function to reuse in $profile

function Convert-Image{
    param($image,$toFormat,$saveTo)
    $baseName = [System.IO.Path]::GetFileNameWithoutExtension($image)
    $img = new-object system.drawing.bitmap $image
    $img.save("$saveTo\$baseName.$toFormat",$toFormat)   
}

Convert-Image -image "C:\windows\Blue Lace 16.bmp" -toFormat gif -saveTo c:\temp

3 comments:

Anil said...

Seems useful... will come back sometime!

Happy Blogging (and scripting)!

odysseus said...

Hey pal,

Thanks for the snippet. it was helpful for me.

Here's a little more enhanced version.

function Convert-Image{
param($image = "", $toFormat="png", $saveTo = "", $removeOriginal=0)

$result = ""
# Check 1: File existance
if ($image -ne $null)
{
if ([System.IO.File]::Exists($image))
{
# Check 2: set default output path
if ($saveTo -eq $null -or $saveTo -eq "")
{
$saveTo = [System.IO.Path]::GetDirectoryName($image)
}

$baseName = [System.IO.Path]::GetFileNameWithoutExtension($image)

trap {"Error while reading the image! Image convertion aborted. Please try again."} $img = new-object system.drawing.bitmap $image

if($img -ne $null)
{
$img.save("$saveTo\$baseName.$toFormat",$toFormat)

if ($removeOriginal)
{
Del $image
}

$img.Dispose()
$result = "$image successfully converted to $toFormat format"
}
}
else
{
$result = "Image $image does not exist. Try again with a relevant image file"
}
}
else
{
$result = "The image name is null or empty. please provide a vaild image file to process. \n Usage : Convert-Image -Image -toformat -saveto "
}
write-output $result
}

# Convert-Image -image "C:\windows\Blue Lace 16.bmp" -toFormat gif -saveTo c:\temp -removeOriginal 1

$hay@Israel said...

Cool :)