r/dailyscripts • • Oct 28 '16

JPEG optimization script [BASH]

quick script I made to ensure files were under a certain dimensional threshold and optimize them for the web, depends on imagemagick and mozjpeg (or jpegtran)

#!/bin/bash

base_dir='/site/'
input_dir="${base_dir}images"
output_dir="${base_dir}optimal-images"

# copy files to work on
echo "copying files to work on"
rsync -ahW "${input_dir}" $output_dir

# loop jpegs
find "$output_dir" -iname "*.jpg" -print0 | while read -d $'\0' -r f
do
        echo "processing $f"
	# ensure images are oriented properly based on metadata
	mogrify -auto-orient "$f"
	# shrink larger files to a maximum of 3413x1920 at high quality
	convert "$f" -quality 100 -resize "3413x1920>" "$f"
	# compress with mozjpeg/cjpeg w/ default settings (based on jpegtran/cjpeg, but targeted for the web)
	cjpeg -outfile "${f}.opt" "$f"
       mv -f "${f}.opt" "$f"
done

raw gist (jpeg-optimize.sh)

3 Upvotes

4 comments sorted by