Batch save images into a new format via PowerShell
Use a PowerShell script to copy all images in a directory and save them into a different image file format.
I recently had a directory full of JPG images which I needed to convert into PNG format. Whilst I could open Adobe Photoshop and process the images one-by-one, batch-processing using PowerShell seemed like it would be more efficient.
To achieve my goal I used the following script, which is adapted from The Scripting Guy:
function ConvertImage{
param ([string]$path)
$path="c:\path\to\files" #path to files
if (Test-Path $path)
{
#Load required assemblies and get object reference
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
foreach($file in (ls "$path\*.jpg")){
$convertfile = new-object System.Drawing.Bitmap($file.Fullname)
$newfilname = ($file.Fullname -replace '([^.]).jpg','$1') + ".png"
$convertfile.Save($newfilname, "png")
$file.Fullname
}
}
else
{
Write-Host "Path not found."
}
};ConvertImage -path $args[0]
Before execution, the script needs to be customised via the following steps:
Step 1: Choose the path
For this script to work, $path
needs to be defined in MS DOS format.
Step 2: Define the image type
Adjust the code to reflect the image type that is being targeted (in my case, .jpg
).
foreach($file in (ls "$path\*.jpg"))
This script uses System.Drawing.Bitmap
which permits conversion to or from BMP, GIF, JPEG, PNG, TIFF and WMF formats.
Step 3: Define the image type
Adjust the code to reflect the change in file extension from .jpg to .png (or whichever the target format is)
$newfilname = ($file.Fullname -replace '([^.]).jpg','$1') + ".png"
Step 4: Define the file extension
Adjust the code to reflect the change in file extension from .jpg to .png (or whichever the target format is)
$convertfile.Save($newfilname, "png")
Step 5: Execute the script
The new images will progressively appear in the same directory as the old.
Comments
5 responses to “Batch save images into a new format via PowerShell”
I had to change the save line to look like this to use the system typed value:
$convertfile.Save($newfilname, [System.Drawing.Imaging.ImageFormat]::PNG)
don’t you want to discard the ‘convertfile object and then delete the original jpg’?
How can i save an image in BMP 16 bits format?.
I managed to save it as BMP (24 bits by default), but how can i change ti 16 bit BMP?