Skip to content

Powershell – Convert BMP to JPG via pipeline (Get-ChildItem)

by Dan Thompson on February 21st, 2012
PowerShell - Convert BMP to JPG

A script to convert a bunch of Bitmap files to Jpegs via PowerShell pipe from Get-ChildItem.

Copy the code below and save it as ‘Convert-ToBmpToJpeg.ps1′.

#Convert-BmptToJpeg.ps1

foreach ($filepath in $input) {
	if (Test-Path $filepath)
	{
		#Load required assemblies and get object reference
		[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
		$convertfile = new-object System.Drawing.Bitmap($filepath.FullName)
		$newfilname = ($filepath.FullName -replace '([^.]).bmp','$1') + ".jpg"
		$convertfile.Save($newfilname, "jpeg")
		"Converting...`t" + $filepath.FullName + "`t->`t" + $newfilname
		$convertfile.Dispose()
	}
	else
	{
		Write-Host "Path not found."
	}
}

Now to call this script, open up PowerShell and navigate to the directory of the saved script. You can now ‘pipe’ a bunch of files into this script. So for example, if I wanted to convert all the bitmaps in my ‘My Pictures’ folder, I’d perform the following command:

 Get-ChildItem -Filter *.bmp -Recurse | .\Convert-BmpToJpeg.ps1 

The first command ‘Get-ChildItem -Filter *.bmp -Recurse’ gets all BMP files from within the folder tree. The rest of the command is to pipe the files collected into the Convert-BmpToJpeg.ps1 script which performs the basic conversion. I would recommend checking the quality of the Jpeg files created…as far as I remember you can set a quality property within this conversion process.

For the next step, you might want to delete all the BMP files (once you’ve checked you’re happy with the quality of the JPEGs). To do this you’ll need to pipe all the BMP files into the Remove-Item Cmdlet. When I do anything like this, I always use the ‘WhatIf’ parameter so I can see the effect without performing the command:

 Get-ChildItem -Filter *.bmp -Recurse | Remove-Item -WhatIf