Optimizing JPEG graphics files with ImageMagick

Optimizing JPEG graphics files with ImageMagick

Created:17 Mar 2017 13:36:30 , in  Host development,  Web development

The other day I had a closer look at some of my websites speed and server load statistics with a view to improving them a little. There are quiet a few methods to achieve that. Google have some nice articles on the subject. Check their "Make the Web Faster" pages if you haven't yet.

One of matters they make a point of on them is how well images you are serving are optimized. Since some of my graphics files were clearly too heavy for the web, I decided on crouching over the subject for a couple of hours. As a result, I automated some bits of image optimization process for my websites using BASH and ImageMagick utility suite.

Automating JPEG files optimization

Below is one of BASH scripts I have written for optimizing JPEG images. It uses one of ImageMagick many utilities called mogrify. The script, I called it optimize_jpegs.sh, when given a directory of JPEG files, and possibly desirable output image quality in percentages, optimizes the files. With quality parameter set to 70%, (default value) my JPEG files were occupying nearly 50% less space when compared to initial numbers, moreover, they lost extremely little of their visual appeal as a result of the treatment.

The script, apart from its main job of optimizing files, counts files being worked on. It gives initial amount of space taken in the directory before and after optimization process has taken place. A basic progress indicator is also being displayed when optimize_jpegs.sh works


Avoiding damage to the original files

Going back to ImageMagick, mogrify, unlike convert, is a utility which overwrites files. It leaves no copies either. Make sure you test optimize_jpegs.sh on copies or remember about how mogrify acts at least . If not careful, you might cause irreparable damage to your original graphics files.

The script

#!/usr/bin/env bash

# script : optimize_jpegs.sh
# description : optimize JPEG images in place
# prerequisites : ImageMagick program suite installed on the system 
# Author : Sylwester Wojnowski
# WWW : wojnowski.net.pl
# Usage : optimize_jpegs.sh directory [quality]
#   directory - path to an existing directory on the system where images in JPEG format are kept
#   quality - percentage in range of 1 - 99, 70% by default
# Example : optimize_jpegs.sh /tmp/my/jpegs 65% 

  printf "Beginning JPEG files optimization ...\n"  
  local source_dir=${1%/}
  local quality=${2:-"70%"}
  local count=0  
  local space_total_raw_before=$(du -hs "$source_dir")
  local space_total_before="${space_total_raw_before/%[[:blank:]]${source_dir}}"

  local space_total_raw_after=
  local space_total_after=

  [[ -z $( which mogrify ) ]] && {
    printf "ImageMagick not installed on the system. Exiting ...\n";
    exit 1;

  [[ ! -d "$source_dir" ]] && {
    printf "$source_dir is not a directory on the system. Exiting ...\n";
    exit 1;

  local p_reg='^([1-9]|[1-9][0-9])%$';
  [[ ! $quality =~ $p_reg ]] && {
    printf "Quality parameter not in range. The correct range is 1 - 99 %. Exiting ...\n"
    exit 1;
  shopt -s extglob;
  while read -r -d ''; do
    mogrify -strip -interlace Plane -quality "$quality" -define jpeg:dct-method=float -sampling-factor 4:2:0 "$REPLY"
    (( count++ ))
    printf '.'
  done < <( find "$source_dir"/*\.jp?(e)g -print0 )
  printf '\n';

  shopt -u extglob  

  space_total_raw_after=$(du -hs "$source_dir")
  printf "Optimization complete!\n"
  printf "  $count JPEG files optimized and saved to: $source_dir.\n" 
  printf "  Total space taken before optimization: %s, Space taken after: %s\n" "${space_total_before}" "${space_total_after}"

optimize_jpegs "$1" "$2"

Use examples

Before invoking it, make optimize_jpegs.sh executable first using chmod command.

Below is how one would use optimize_jpegs.sh on the text terminal.

Optimizing JPEG files in /tmp/my/jpegs to 70% quality ( default ).

optimize_jpegs.sh /tmp/my/jpegs

Optimizing JPEG files in /tmp/my/jpegs to 60% quality.

optimize_jpegs.sh /tmp/my/jpegs 60%

Final thoughts

The script presented in this article relies on ImageMagick. I built it for optimizing JPEG files as they were my primary concern at the time of writing it. Nonetheless, based on the script and due to ImageMagick being such a wonderfully versatile tool, similar utility can be built fairly easily for optimizing EXIFs or PNGs among other graphics file formats. I hope you'll find optimize_jpegs.sh useful.

This post was updated on 17 Mar 2017 17:05:25

Tags:  BASH ,  image ,  ImageMagick 

Author, Copyright and citation


Sylwester Wojnowski

Author of the above article, Sylwester Wojnowski, is sWWW admin and owner.He enjoys doing Maths and studying algorithms, writing code in scripting and command languages, Thrash Metal music and playing electric guitar.


©Copyright, 2017 Sylwester Wojnowski. This article may not be reproduced or published as a whole or in parts without permission from the author. If you share it, please give author credit and do not remove embedded links.

Computer code, if present in the article, is excluded from the above and licensed under GPLv3.


Cite this article as:

Wojnowski, Sylwester. "Optimizing JPEG graphics files with ImageMagick." From sWWW - Code For The Web . https://wojnowski.net.pl//main/index/optimizing-jpeg-graphics-files-with-imagemagick