Skip to content

Instantly share code, notes, and snippets.

@magnusdahlstrand
Last active December 15, 2015 09:29
Show Gist options
  • Save magnusdahlstrand/5239303 to your computer and use it in GitHub Desktop.
Save magnusdahlstrand/5239303 to your computer and use it in GitHub Desktop.
Simple png/jpg -> optimised jpg script
#!/usr/bin/env bash
function cleanup() {
rm -rf "$temp_dir" > /dev/null 2>&1
}
trap cleanup EXIT
function setup() {
temp_dir='/tmp/imgcmprs'
mkdir -p "$temp_dir"
}
if [[ -z "$1" ]]; then
echo 'usage: imgcmprs path [...]' >&2
exit 1
fi
setup
current=0
total=$#
for file in "$@"; do
current=$(( $current + 1 ))
if [[ ! -f "$file" ]]; then
echo 'input file "$file" is not a regular file' >&2
exit 2
fi
file_dir=$(dirname "$file")
file_name=$(basename "$file")
file_base="${file_name%.*}"
file_ext="${file_name##*.}"
temp_file=$(mktemp "$temp_dir/XXXXXXXX")
mv "$temp_file" "$temp_file.jpg"
temp_file="$temp_file.jpg"
echo -en "Processing $current of $total\r"
if [[ "$file_ext" != "jpg" ]]; then
convert "$file" -quality 100 "$temp_file"
else
cp "$file" "$temp_file"
fi
jpegoptim -v --max=82 --strip-all --strip-icc "$temp_file" > /dev/null 2>&1
if [[ $? != 0 ]]; then
echo 'Processing of file "$file" did not work.'
exit 3
fi
mv "$temp_file" "$file_dir/$file_base.jpg"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment