How to convert lossless PNG to lossless WEBP via macOS terminal

Install libwebp first:

brew install libwebp

Convert all the PNGs to WEBP and touch them to have the same datetime as the original PNG files.

find ~/directory -type f -name "*.png" -exec sh -c 'cwebp -lossless -q 100 "$0" -o "${0%.png}.webp" && touch -r "$0" "${0%.png}.webp"' {} \;

Then delete the original PNG files.

find ~/directory -type f -name "*.png" -exec sh -c 'rm "${0%}"' {} \;

Putting it alltogether

find ~/directory -type f -name "*.png" -exec sh -c 'cwebp -lossless -q 100 "$0" -o "${0%.png}.webp" && touch -r "$0" "${0%.png}.webp"' {} \; && 
find ~/directory -type f -name "*.png" -exec sh -c 'rm "${0%}"' {} \;

Possible improvements (that I’ll probably never get around to)

  1. Do not delete the PNG file if the WEBP ends up larger — rare, but it does happen.
  2. If the WEBP ends up larger, delete it.

Leave a Reply