Created
November 22, 2025 16:36
-
-
Save tuyendq/946adb2d5f41aed5620d01194e338202 to your computer and use it in GitHub Desktop.
Powershell script to convert all .jpg in a folder to .webp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Set the desired quality (0 to 100). 80 is a good default balance. | |
| $Quality = 80 | |
| # --- User Configuration --- | |
| # 1. Define the directory where the conversion should start. | |
| # '.' means the current directory where the script is run. | |
| $StartFolder = "." | |
| # 2. Define the path to the cwebp executable. | |
| # - If it's in your system's PATH, just use 'cwebp'. | |
| # - Otherwise, provide the full path, e.g., 'C:\WebPTools\bin\cwebp.exe'. | |
| $cwebpPath = "cwebp" | |
| # --- Script Logic --- | |
| Write-Host "--- Starting WebP Conversion Script ---" -ForegroundColor Yellow | |
| Write-Host "Target Folder: $(Resolve-Path $StartFolder)" -ForegroundColor Cyan | |
| Write-Host "Quality Setting: $Quality" -ForegroundColor Cyan | |
| Write-Host "cwebp Path: $cwebpPath" -ForegroundColor Cyan | |
| # Check if cwebp is available | |
| if (-not (Get-Command $cwebpPath -ErrorAction SilentlyContinue)) { | |
| Write-Host "ERROR: cwebp executable not found at '$cwebpPath'." -ForegroundColor Red | |
| Write-Host "Please ensure cwebp is in your system's PATH or update the `$cwebpPath variable." -ForegroundColor Red | |
| exit 1 | |
| } | |
| # Recursively find all .jpg files | |
| $FilesToConvert = Get-ChildItem -Path $StartFolder -Filter "*.jpg" -Recurse -File | |
| if ($FilesToConvert.Count -eq 0) { | |
| Write-Host "No .jpg files found to convert." -ForegroundColor Green | |
| exit 0 | |
| } | |
| Write-Host "Found $($FilesToConvert.Count) JPG file(s). Starting conversion..." -ForegroundColor Green | |
| # Loop through each file and run cwebp | |
| foreach ($File in $FilesToConvert) { | |
| # Define the output file path (changes the extension to .webp) | |
| $OutputFilePath = Join-Path -Path $File.DirectoryName -ChildPath "$($File.BaseName).webp" | |
| Write-Host "Converting: $($File.Name) --> $($OutputFilePath)" -ForegroundColor White | |
| # Execute the cwebp command | |
| & $cwebpPath -q $Quality "$($File.FullName)" -o "$OutputFilePath" | |
| # Optional: Check the exit code of the cwebp command | |
| if ($LASTEXITCODE -ne 0) { | |
| Write-Host "WARNING: cwebp returned an error code ($LASTEXITCODE) for $($File.Name)." -ForegroundColor Yellow | |
| } | |
| } | |
| Write-Host "--- Conversion Complete! ---" -ForegroundColor Green |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment