How to generate sprite image for javascript app

Composite sprite images are one of the optimization methods for displaying images. Many small files are compressed to single larger file when using it you gain:

  • One big request instead of many small requests;
  • Possibly better compression;

In my case, I needed to rapidly display one of about 100 images, and I would need to be sure that image is cached by the browser, as total display time of the image is less than 0.3sec (so any network roundtrips would just totally destroy the experiment.

To my astonishment, it turned out that there was no simply googleable cli tool that would take a folder with images and output composite sprite image and a CSS file.

The spritesmith-cli tool

To create sprite image you can use node package named spritesmith-cli, apart from the cli, you'll need to install proper "engine" to actually do the image manipulation, I choose pixelsmith which has no external dependencies and uses native nodejs APIs.

So the install command is:

# Please take care when installing packages globally,
# I installed it in a docker container so any rogue package
# won't directly harm my OS (unless it leverages docker exploits)
npm install -g spritesmith-cli pixelsmith

Then you need to create a configuration file named .spritesmith.js

'use strict';
module.exports = {
    src: 'images/*.{png,gif,jpg}',
    destImage: './glyphs.png',
    destCSS: './glyph.css',
    imgPath: '/assets/glyph.png',
    padding: 2,
    algorithm: 'binary-tree',
    engine: 'pixelsmith',
    cssOpts: {
        cssClass: function (item) {
            return '#glyph-' + item.name;
        }
    }
};

Then assuming that images are in the images folder, after calling spritesmith command you'll get glyphs.png file that contains the images and glyphs.css that contains the CSS.

Optimize the generated png

Generated .png file was not really optimized, so I just ran optipng on it which decreased the image size to 50% of the original.