Last Updated: January 06, 2019
·
554
· skyzyx

PNG/JPG → WebP

Assuming you're adding this to a Makefile (which requires all $ to be $$), and the PNG/JPG files are in a directory called ./remote-assets, you can use the following to produce a WebP version of the JPG/PNG file.

# PNG
find ./remote-assets -type f -name '*.png' | xargs -P $$(nproc) -I {} bash -c 'if [ ! -f "$${1%.png}.webp" ]; then cwebp -mt -q 75 $$1 -o "$${1%.png}.webp"; fi;' _ {} \;

# JPG
find ./remote-assets -type f -name '*.jpg' | xargs -P $$(nproc) -I {} bash -c 'if [ ! -f "$${1%.jpg}.webp" ]; then cwebp -mt -q 75 $$1 -o "$${1%.jpg}.webp"; fi;' _ {} \;

This will:

  1. Find all .png/.jpg files in the directory (recursively)
  2. Pass the list of matches to xargs
  3. Determine the number of CPU cores you have
  4. Spin up that many threads in order to parallelize the work
  5. Only run if the .webp version does not already exist
  6. Use Bash to call cwebp
  7. Output the file with the same name, but with a .webp file extension