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