Skip to content

Image Compression and Renaming Script

This guide provides instructions on how to use a PowerShell script and a batch file to compress image files and rename them sequentially.

Step 1:

Install ImageMagick via Chocolatey or download it from the official website.

Run Command Prompt or PowerShell as Administrator To install ImageMagick via Chocolatey, run:

choco install imagemagick

Step 2:

Files

  1. compress_images.ps1: PowerShell script to compress and rename images.
  2. run_compression.bat: Batch file to execute the PowerShell script.

PowerShell Script: compress_images.ps1

compress_images.ps1

The PowerShell script performs the following tasks:

  • Compresses each image file to a target size (in this case, 0.6 MB).
  • Renames each file with a sequential prefix.

Script Details

powershell
# Ask if user wants to use original file names
$useOriginalNameInput = Read-Host "Use original file names? (true/false, default: false)"
if ([string]::IsNullOrEmpty($useOriginalNameInput)) {
    $useOriginalName = $false
} else {
    $useOriginalName = [bool]$useOriginalNameInput
}

# Prompt for prefix if original filenames are not used
if (-not $useOriginalName) {
    $prefix = Read-Host "Enter the prefix for the new filenames"
}

# Check if user input is empty for the next parameters, then assign default values
$numInput = Read-Host "Enter the starting number for the filenames (default: 1)"
if ([string]::IsNullOrEmpty($numInput)) {
    $num = 1
} else {
    $num = [int]$numInput
}

$targetSizeMBInput = Read-Host "Enter the target size in MB (default: 0.4)"
if ([string]::IsNullOrEmpty($targetSizeMBInput)) {
    $targetSizeMB = 0.4
} else {
    $targetSizeMB = [float]$targetSizeMBInput
}

$tempFolderInput = Read-Host "Enter the folder name where the images will be saved (default: temp)"
if ([string]::IsNullOrEmpty($tempFolderInput)) {
    $tempFolder = "temp"
} else {
    $tempFolder = $tempFolderInput
}

# Initialize compression quality and thresholds
$quality = 75
$minQuality = 10

$processedCount = 0  # Counter for processed files

# Create the target folder if it doesn't exist
if (-not (Test-Path -Path $tempFolder)) {
    New-Item -ItemType Directory -Path $tempFolder
}

# Get all jpg files in the current directory
$files = Get-ChildItem -Filter *.jpg
$totalFiles = $files.Count  # Total number of files for progress tracking

foreach ($file in $files) {
    # Determine the new name based on $useOriginalName
    if ($useOriginalName) {
        $newName = $file.Name
    } else {
        $newName = "{0}{1}.jpg" -f $prefix, $num
    }
    $newPath = Join-Path $tempFolder $newName

    try {
        # Temporary file name for compression
        $tempFileName = [System.IO.Path]::Combine($tempFolder, [System.IO.Path]::GetFileNameWithoutExtension($file.Name) + "_temp.jpg")

        # Use ImageMagick to compress the image without resizing
        $cmd = "magick '$($file.FullName)' -quality $quality '$tempFileName'"
        iex $cmd  # Execute command

        # Check the file size and reduce quality if needed
        $fileSizeMB = (Get-Item $tempFileName).Length / 1MB

        while ($fileSizeMB -gt $targetSizeMB -and $quality -gt $minQuality) {
            $quality -= 5
           
            # Compress again with reduced quality
            $cmd = "magick '$($file.FullName)' -quality $quality '$tempFileName'"
            iex $cmd
            $fileSizeMB = (Get-Item $tempFileName).Length / 1MB
        }

        # Move the final compressed image to the target folder
        Move-Item -Force $tempFileName $newPath

        # Increment the file name counter if prefix-based names are used
        if (-not $useOriginalName) {
            $num++
        }

        # Increment the processed file count
        $processedCount++
        
        # Display real-time progress
        Write-Host "$processedCount of $totalFiles files processed..."

    } catch {
        Write-Host "Failed to process $($file.FullName)"
        Write-Host $_.Exception.Message
    }
}

# Final message showing total processed files
Write-Host "$processedCount files have been processed and saved to the '$tempFolder' folder."
Write-Host "Processed by Soumojit Shome"

Step 3:

Batch File: run_compression.bat

run_compression.bat

The batch file automates the execution of the PowerShell script.

Batch File Details

batch
@echo off

REM Change directory to the folder containing the files
cd /d "%~dp0"

REM Call the PowerShell script to compress images
powershell -ExecutionPolicy Bypass -File compress_images.ps1

echo All files have been renamed and compressed.
echo Processed by Soumojit Shome.
pause

How to Use

  1. Install ImageMagick :

    • Install ImageMagick via Chocolatey or download it from the official website.
    • Run Command Prompt or PowerShell as Administrator
    • To install ImageMagick via Chocolatey, run: choco install imagemagick
  2. Prepare the Scripts :

    • Save the PowerShell script as compress_images.ps1.
    • Save the batch file as run_compression.bat.
  3. Place the Scripts in the Target Directory :

    • Move both compress_images.ps1 and run_compression.bat to the directory containing the JPG files you want to compress and rename.
  4. Run the Batch File :

    • Double-click run_compression.bat to execute the compression and renaming process.
  5. Check the Results :

    • The images will be compressed to the target size and renamed sequentially with the prefix newname.

Notes

  • Ensure that the target directory contains only the images you want to process.

By following these steps, you can easily compress and rename your image files using the provided PowerShell script and batch file.