Skip to content

Instantly share code, notes, and snippets.

@Coornail
Last active March 21, 2020 02:10
Show Gist options
  • Save Coornail/5a38ff940855c2b316a9 to your computer and use it in GitHub Desktop.
Save Coornail/5a38ff940855c2b316a9 to your computer and use it in GitHub Desktop.
#!/bin/bash
#line break for "for"
IFS=`echo -en "\n\b"`
# Function to optimize a jpeg image.
function optimize() {
ORIGINAL_FILE_SIZE=`du -b $1 | awk {'print $1'}`
jpegtran -copy none -optimize -perfect -outfile "$1-opt" "$1"
OPTIMIZED_FILE_SIZE=`du -b "$1-opt" | awk {'print $1'}`
if [ $ORIGINAL_FILE_SIZE -gt $OPTIMIZED_FILE_SIZE ]
then
mv -f "$1-opt" "$1"
echo -n '.'
else
rm "$1-opt"
echo -n 'x'
fi
}
if [ -z "$1" ]
then
DIRECTORY="."
else
DIRECTORY="$1"
fi
echo "[+] Optimizing jpegs under $DIRECTORY"
cd $DIRECTORY
STARTER_SIZE=`du -b $DIRECTORY | awk {'print $1'}`
echo "[i] Starting size: $STARTER_SIZE"
export -f optimize
PARALLEL_SHELL=/bin/bash \
parallel --no-notice --env optimize optimize "{}" ::: `ls $DIRECTORY/*.jpg`
echo '';
END_SIZE=`du -b $DIRECTORY | awk {'print $1'}`
PERCENT=`echo "scale = 5;$END_SIZE/$STARTER_SIZE*100" | bc`
echo "[i] End size: $END_SIZE ($PERCENT%)"
IFS=$ORIGIFS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment