Optimizing Images

Published July 16, 2018

This blog lives entirely in Dropbox. I consider it a blesssing: I can access it from virtually anywhere, provided I have an Internet connection. However, it does mean it’s left up to me to organize the files.

Given the title of this post, images are the focus so I want to:

  1. keep a relatively flat directory structure while
  2. keeping filesize to a minimum and
  3. reduce the probability of name collisions.

Directory Structure

All “assets” go in a /_static/ directory. Like my posts, I create a directory for each year and the files go in there. For example, an image for a post in 2018 would look like /_static/2018/example.png, that’s it.

Compressing Images

If I have an Internet connection my go-to is TinyPNG. The service is easy to use, supports JPEG & PNG, and has good compression results.

If I have no Internet connection my go-to is the imagemin-cli. It’s slower & typically doesn’t have as good compression results but, it’s installed via npm (npm i -g imagemin-cli) which provides solid cross-platform support.

Preventing Collisions

Appending the content hash to the filename of an image provides a reasonable way of reducing the chances that I’ll have two (unique) images collide, even if they share the same base filename. It’s the same strategy that asset-revision tools like gulp-rev-all1 use.

Automation

Given these requirements, I wanted a way to automate the process. Naturally, I created a small2 shell script aptly named optimg. It will handle the task of compressing (by using the previously-mentioned imagemin-cli) & renaming or simply just renaming images.

The script lives in my dotfiles repo. It’s been tested on Bash 4.x in a macOS & Linux environment. To install, the easiest method is to add it to your $PATH.


  1. N.B. I’m a huge fan of Gulp & use it in most projects.↩︎

  2. Around 100 sloc with adequate whitespace & comments.↩︎

Last modified January 31, 2019  #dev   #blot   #bash   #productivity 


← Newer post  •  Older post →