Created
March 10, 2026 23:03
-
-
Save nateberkopec/cb67922f0d60aecc99e16ee524cc45eb to your computer and use it in GitHub Desktop.
Convert PNGs > 100KB to optimized JPEGs for Cloudflare Polish
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
| #!/bin/bash | |
| # Convert PNGs > 100KB to optimized JPEGs for Cloudflare Polish webp conversion | |
| # Usage: ./png_to_jpeg.sh [directory] | |
| # Requires: ImageMagick (convert), jpegoptim | |
| set -euo pipefail | |
| DIR="${1:-.}" | |
| QUALITY=85 | |
| MIN_SIZE_KB=100 | |
| DRY_RUN="${DRY_RUN:-false}" | |
| command -v convert >/dev/null || { echo "Error: ImageMagick not found. Install with: brew install imagemagick"; exit 1; } | |
| command -v jpegoptim >/dev/null || { echo "Error: jpegoptim not found. Install with: brew install jpegoptim"; exit 1; } | |
| converted=0 | |
| skipped=0 | |
| total_saved=0 | |
| while IFS= read -r -d '' png; do | |
| size_kb=$(( $(stat -f%z "$png" 2>/dev/null || stat -c%s "$png" 2>/dev/null) / 1024 )) | |
| if [ "$size_kb" -lt "$MIN_SIZE_KB" ]; then | |
| skipped=$((skipped + 1)) | |
| continue | |
| fi | |
| jpeg="${png%.png}.jpg" | |
| if [ "$DRY_RUN" = "true" ]; then | |
| echo "[dry-run] $png (${size_kb}KB) -> $jpeg" | |
| converted=$((converted + 1)) | |
| continue | |
| fi | |
| # Convert to JPEG, flatten alpha channel to white background | |
| convert "$png" -flatten -quality "$QUALITY" "$jpeg" | |
| # Optimize the JPEG in place (strip metadata, keep quality ceiling) | |
| jpegoptim --strip-all --max="$QUALITY" -q "$jpeg" | |
| jpeg_size_kb=$(( $(stat -f%z "$jpeg" 2>/dev/null || stat -c%s "$jpeg" 2>/dev/null) / 1024 )) | |
| saved=$((size_kb - jpeg_size_kb)) | |
| total_saved=$((total_saved + saved)) | |
| echo "$png (${size_kb}KB) -> $jpeg (${jpeg_size_kb}KB) [saved ${saved}KB]" | |
| # Remove original PNG | |
| rm "$png" | |
| converted=$((converted + 1)) | |
| done < <(find "$DIR" -type f -iname '*.png' -print0) | |
| echo "" | |
| echo "Done: ${converted} converted, ${skipped} skipped (<${MIN_SIZE_KB}KB), ~${total_saved}KB saved" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment