Schneimi’s Dev Weblog

Batch generated spritemap and css with ImageMagick on Windows

Posted in CSS,Eclipse by schneimi on February 3, 2013
Tags: , , , ,

I had the idea of one click generated spritemaps for quiet a while, but never had time to look into it and kept going on manually creating them by online service for my projects. When I read an article about command line css spriting, I was amazed, how easy the map can be built using ImageMagick and that it’s even possible to read width and height from the images. Nevertheless, the automated generation of the css code was still missing. Especially when the icon order changes, this is still annoying work.

This made me think…we know how to create the spritemap and can also read the width and height of each sprite with ImageMagick, so the only thing that is left, is to cycle through the sprites, read width or height from them and write the css code to a file. Then I dig out some of my Windows batch skills and came up with the following little batch script. It’s not that easy to understand, so I made some comments on the relevant lines.


@echo off
rem /* prepare environment */
setlocal EnableDelayedExpansion
del spritemap.png
del spritemap.css
set position=0
set sign=
rem /* execute imagick convert and create a horizontal (use -append for vertical) sprite map, using black as transparency color */
convert.exe *.png -transparent black +append spritemap.png
rem /* loop through all png files */
for /f %%f in ('dir /B *.png') do (
  rem /* for each file execute imagick identify */
  for /f "tokens=3 delims= " %%i in ('identify.exe %%f') do (
    rem /* parse the image width from the result (use tokens=2 for height in a vertical sprite map) */
    for /f "tokens=1 delims=x" %%j in ('echo %%i') DO (
      rem /* for each image append this css code to the spritemap.css file */
      echo .ui-%%~nf { background-image: url^("../img/spritemap.png"^)^; background-position: !sign!!position!px 0^; }>>spritemap.css
      rem /* calculate the next background position */
      set sign=-
      set /a position=%%j+position

In my case the css is for custom icons in jQuery Mobile. This example only runs with all files in one folder, but paths can be adapted easily, as well as the css output. Also further image optimization with tools like optipng, as described in the mentioned article, can be easily added.

I Hope this makes someone as much happy as I are, finally having found a fully automated solution. For me it’s a perfect solution, because I already use batch-scripts to merge and pack all css and js files with one click in eclipse and I just had to add this script to my existing batch file.