Skip to content

Instantly share code, notes, and snippets.

@patrickfav
Created September 21, 2024 22:24
Show Gist options
  • Save patrickfav/e8ca47bddf37eb306f6d3713dc8d6598 to your computer and use it in GitHub Desktop.
Save patrickfav/e8ca47bddf37eb306f6d3713dc8d6598 to your computer and use it in GitHub Desktop.
A Powershell Script that converts all png files recusivly in given folder (and subfolders) when the resulting jpeg is smaller than the png and the png does not contain transparency. Requires Image Magick to be available in PATH.
$sourceFolder = "C:\path\to\pngs"
$sumSavedKb = 0
# Get all PNG files recursively
Get-ChildItem -Path $sourceFolder -Recurse -Filter *.png | ForEach-Object {
$file = $_.FullName
$jpgFile = [System.IO.Path]::ChangeExtension($file, "jpg")
# Get the old file size (in kB)
$oldfilesize = [Math]::Round((Get-Item -LiteralPath $file).Length / 1KB, 2)
# Check if the PNG file has transparency using ImageMagick
$hasTransparency = magick identify -format "%[channels]" "$file" | Select-String -Pattern "a"
if ($hasTransparency)
{
Write-Host "Skipping $file because it contains transparency."
}
else
{
# Run the ImageMagick convert command with quality and compression
magick -quality 70 -compress JPEG "$file" "$jpgFile"
# If the conversion was successful
if (Test-Path -LiteralPath $jpgFile)
{
# Get the new file size (in kB)
$newfilesize = [Math]::Round((Get-Item -LiteralPath $jpgFile).Length / 1KB, 2)
# Check if the new JPG is larger than the original PNG
if ($newfilesize -lt $oldfilesize)
{
# Calculate the size saved
$savedSpace = $oldfilesize - $newfilesize
$sumSavedKb += $savedSpace
# Print log statement with file sizes and saved space
Write-Host "Convert $file to $jpgFile ($oldfilesize kB > $newfilesize kB), saved $savedSpace kB"
# Remove the original PNG file
Remove-Item -LiteralPath $file
}
else
{
# If the new JPG is larger, delete it and keep the original PNG
Remove-Item -LiteralPath $jpgFile
Write-Host "Skipped converting $file, JPEG is larger."
}
}
else
{
Write-Host "Failed to convert $file"
}
}
}
# Print total space saved at the end
Write-Host "Compression finished, saved $([Math]::Round($sumSavedKb, 2) ) kB"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment