Satya's blog - Spriting with Imagemagick

Mar 29 2012 07:20 Spriting with Imagemagick

A sprite sheet is a single image which has all the images used on a web page. each image on a web page has overhead of the image file format itself, plus network overhead (connection establishment, which is not a huge concern with pipelining, and extra transfer time negotiating TCP headers, HTTP headers, time for the web server to find the file.... it adds up).

If done right, the single image of the sprite sheet takes fewer bytes and loads faster than multiple individual images. This works best when the individual images are smaller "accent" images, not large photos of your product.

CSS is used to show the appropriate image from the sheet. Typically, the sprite sheet is placed as the background on a div which is the right size to show just the part of the sheet containing the appropriate image. This "window" is set by setting a width and height on the div, and then backgrond-position the sheet into the right place. The position is the offset of the image coordinates into the sheet, with negative signs.

.some-div {
width: 20px;
height: 10px;
background: url(/images/sprites.png);
background-position: -54px -90px;
}

This says to show a 20x10 portion of the sprite sheet image starting at 54px X-offset into the image and 90px Y-offset. Why negative? Because background-position needs to "pull" the sprite sheet up and to the left so as to offset into it. Think of the div as a window into the sheet. Backgrond-position moves the sheet around behind the window. It does not move the window.

How to make a sprite sheet from individual images? Stick your sprite candidate images into a sprites directory or whatever and do this:

convert -background transparent sprites/* +append sprites.png

Transparent background is a best practice, so that any background colors on your page show through and you don't get a rectangular patch. If you know what the background color is, you can use it, as transparency can actually increase the size of the final image.

+append causes the end image to be horizontal which is another best practice. You can combine multiple convert commands to make a more square sprite sheet. First horizontally combine each row, then vertically combine the rows:

convert -background transparent row1/* -append row1.png
convert -background transparent row2/* -append row2.png

convert -background transparent row1.png row2.png +append sprites.png

Tag: howto