Skip to content

Instantly share code, notes, and snippets.

@Brainiarc7
Forked from alanorth/compress.sh
Last active May 14, 2023 13:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Brainiarc7/0a4a87b3c5dbf1653dc4 to your computer and use it in GitHub Desktop.
Save Brainiarc7/0a4a87b3c5dbf1653dc4 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# exit on first error
set -o errexit
readonly IMG="$1"
readonly GM_BINARY=/usr/local/bin/gm
readonly MV_BINARY=/bin/mv
readonly JPEGTRAN_BINARY=/usr/local/bin/jpegtran
# Lossless operations (remove metadata, optimize compression)
# See: http://www.bookofspeed.com/chapter5.html
optimize() {
local filename=$1
local tempfile=$RANDOM
printf "%s: Lossless optimizations...\n" $filename
$JPEGTRAN_BINARY -copy none -optimize -outfile $tempfile $filename
$MV_BINARY $tempfile $filename
}
# 2.0MB -> 800k, like compressor.io, from original camera image.
# reduce quality, enable progressive/interlace, and scale image
#
# 40-60% size is recommended, depending on your target / bandwidth
# 80% quality is recommended
trim_and_scale() {
local filename=$1
local tempfile=$RANDOM
printf "%s: Converting to 80 quality and scaling...\n" $filename
$GM_BINARY convert $filename -filter triangle -resize 40% -gravity Center -quality 80 -type TrueColor -interlace Line $tempfile
$MV_BINARY $tempfile $filename
}
optimize $IMG
trim_and_scale $IMG

3.6MB image:

$ ls -lh DSC_0685.JPG 
-rw-r--r-- 1 aorth wheel 3.6M Oct 12 20:03 DSC_0685.JPG

Compress:

$ ~/src/compress.sh DSC_0685.JPG 
DSC_0685.JPG: Lossless optimizations...
DSC_0685.JPG: Converting to 80 quality and scaling...

A fraction of the size, with no noticeable loss of quality!

$ ls -lh DSC_0685.JPG
-rw-r--r-- 1 aorth wheel 336K Oct 12 20:03 DSC_0685.JPG

The resulting file is much more appropriate than the original for sharing on the web / email.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment