Skip to content

Instantly share code, notes, and snippets.

@alanorth
Last active August 29, 2015 14:07
Show Gist options
  • Save alanorth/e0ae338da97e7da53dcc to your computer and use it in GitHub Desktop.
Save alanorth/e0ae338da97e7da53dcc to your computer and use it in GitHub Desktop.
Image compression like compressor.io... but with open source tools. It's easier than you think!
#!/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