Blob


1 CSS sprites are a nice idea, stolen from the game developers I think,
2 that consist to merge all the images you need in a single one and
3 download only that. I will not prove that it's best than downloading
4 *n* images, but it should clear that downloading a file, albeit a bit
5 bigger, requires less TCP segments going back and forth.
7 The other day I needed a CSS sprite. Being the lazy person I am, right
8 after The GIMP was open I thought that I didn't want to do the math.
10 After a bit of searching, I found a post where the author wrote a
11 script to generate the sprites (and the relative css file) with image
12 magick. I have lost that link, and the history of my browser doesn't
13 help. I remember that the domain name contains "php", but nothing
14 more. However, I rewritten the script, so it better fits my needs.
16 The idea is to join all the image using `convert(1)` and then generate
17 a CSS file with the offsets using `identify(1)`. Both programs should
18 come along with imagemagick.
20 Here's the script
22 ```sh
23 #!/bin/sh
25 convert sprites/* -append img/sprites.png
27 for i in sprites/*; do
28 identify -format '%W %H %f\n' $i
29 done | awk '
30 function fname(path) {
31 sub (".png", "", path)
32 return path
33 }
35 BEGIN {
36 y = 0
38 print "%sprite-base {"
39 print " background-image: url(/img/sprites.png);"
40 print " background-repeat: no-repeat;"
41 print "}"
42 print ""
43 }
45 {
46 width = $1
47 height = $2
48 class = fname($3)
50 print "%sprite-" class " {"
51 print " @extend %sprite-base;"
52 if (y == 0)
53 print " background-position: 0 0;"
54 else
55 print " background-position: 0 -" y "px;"
56 print "}"
57 print ""
59 y += height;
60 }
61 ' > scss/_sprites.scss
62 ```
64 Assuming that the images are within `sprites/` and all of them are png
65 files, this script will generate the sprite in `img/sprites.png` and a
66 SASS file in `sass/_sprits.scss` with one placeholder for every image
67 (the naming scheme is `%sprite-$NAMEFILE` with the `$NAMEFILE` being
68 the file name without extension).
70 It should be trivial to edit to handle pure CSS output, and eventually
71 other image formats.