Image compression from the command line

Responsive image

Here’s a small script to compress JPEG images in a folder. Useful to save a few kilobytes of bandwith when serving images from your website.

I might improve this script in the future to include more compression tools and/or file extensions.

#!/bin/bash

for f in *.jpg *.JPG *.jpeg *.JPEG
do
    echo -en "Converting ${f} ... "
    kb_orig=`du -k "${f}" | cut -f1`
    convert -quality 70 ${f} ${f}
    kb_after=`du -k "${f}" | cut -f1`
    pct_gain=`expr ${kb_after} \* 100 / ${kb_after}`
    echo " (${kb_orig}kb ==> ${kb_after}kb) DONE - ${pct_gain}%."
done

To generate highly compressed thumbnails.

#!/bin/bash

# Thumbnail generator

MEDIA_DIR="/path"

cd ${MEDIA_DIR}

# CONVERT
for f in ${MEDIA_DIR}/*
do
    complete_filename=$(basename "$f")
    extension="${f##*.}"
    full_filename="${f%.*}"
    #echo $complete_filename $full_filename $extension
    echo -ne "Converting ${complete_filename} ... "
    kb_orig=`du -k "${f}" | cut -f1`
    convert -define peg:size=500x500 ${f} \
        -auto-orient -thumbnail 500x500 -unsharp 0x.5 ${full_filename}_thumb.gif
    kb_after=`du -k "${full_filename}_thumb.gif" | cut -f1`
    pct_gain=`expr 100 - ${kb_after} \* 100 / ${kb_orig}`
    echo -e "(${kb_orig}kb ==> ${kb_after}kb) \033[96m${pct_gain}\033[39m%."
done
Written on July 20th, 2017 by Samy Gejzenblozen

Tags:


Social networks

You may also enjoy:

Convert FLAC to mp3 like a hacker

Convert FLAC to mp3 like a hacker

#system #linux

So you need to convert a bonch of FLAC files to mp3 and your best search engine only recommands you online file converters that nobody trusts ore require a paid subscription to work. Don't worry, *there's always a way*, and even better, a true ***hacker style*** way to achieve this! This procedure works for MacOS through Brew, but you should b... Read more

20 Feb 2019 - less than 1 minute read
Blockchain and IoT

Blockchain and IoT

#blockchain #linux

Here's a small script to open a JavaScript interface to interact with an IoT device. This interface can then be easily incorporated in a larger Blockchain project with real tangible everyday life objects. I'll cover the Blockchain aspect of this project in another article, focusing on *Hyperledger*. The IoT device I'll be using for this project... Read more

20 Aug 2017 - 2 minute read