Skip to content

Instantly share code, notes, and snippets.

@rectangular
Created April 23, 2020 00:20
Show Gist options
  • Save rectangular/5999ba3b21e540ffb3559107726d551d to your computer and use it in GitHub Desktop.
Save rectangular/5999ba3b21e540ffb3559107726d551d to your computer and use it in GitHub Desktop.
Convert multiple PNG images to JPGs using the guetzli encoder. Threaded.
#!/bin/bash
# This requires the guetzli jpg encoder:
# https://github.com/google/guetzli/
# Set the desired max quality
# Quality setting of 84 is the lowest google/guetzli allows :(
# Use my fork of guetzli if you would like to use lower quality settings
# https://github.com/rectangular/guetzli
QUALITY=84
# set max number of threads your processor can handle
MAX_THREADS=8
command -v guetzli >/dev/null 2>&1 || { echo >&2 "Error: guetzli not found. Please install. (https://github.com/google/guetzli/). Aborting."; exit 1; }
# enable job control
set -m
echo "Converting all .png images in this folder to .jpg using guetzli encoder"
# create output directory if needed
if [ ! -d out ]; then
mkdir out
fi
convert()
{
f=$1
filename=$2
q=$3
guetzli --quality $q $f out/$filename.jpg
echo "converted: $f -> out/$filename.jpg at $q quality"
}
for f in *.png; do
q=$QUALITY
filename="${f%.*}"
# Adjust export quality based on filename
# containing: @1x, @1.5x or @2x.
# Guetzli doesn't do as well with really
# low quality settings. Consider adding
# 20-45% higher quality than usual for
# standard JPG compression. Fortunately,
# the filesize will likely still be
# smaller than a typical JPEG export/convert.
if [[ $f == *"@1x"* ]]; then
q=$QUALITY
elif [[ $f == *"@1.5x"* ]]; then
q=80
elif [[ $f == *"@2x"* ]]; then
q=65
fi
# Limit concurrent threads
while [ `jobs | wc -l` -ge $MAX_THREADS ]; do
sleep 5
done
echo "starting task for: $f"
convert "$f" "$filename" "$q" &
done
# wait for tasks to complete
while [ 1 ]; do fg 2> /dev/null; [ $? == 1 ] && break; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment