Skip to content

Dear Internet Explorer user: Your browser is no longer supported

Please switch to a modern browser such as Microsoft Edge, Mozilla Firefox or Google Chrome to view this website's content.

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

No comments have yet been submitted. Be the first!

Have Your Say

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.