January 3, 2011

[SOLVED]Building CSS sprites with Bash & Imagemagick

If you want to automatically generate image sprites - css file just use this script
$ spriteit.sh button button '*.png'

Output:
Generating sprite file...
executing: convert button_disabled.png button_hover.png button.png button_selected.png -append button/button-sprite.png
Sprite complete! - Creating css & test output...
#1 done
#2 done
#3 done
#4 done

Complete! - 4 sprites created, css written & test page output.

Script source:
#!/bin/bash

# uses imagemagick to stich together all images in a folder and
# then writes a css file with the correct offsets along with a
# test html page for verification that its all good

if [ $# -gt 0 ]
then

if [ 'x' != 'x'$4 ]
then
ext2=.$4; # the extension to iterate over for input files
else
ext2=".png"; # the extension to iterate over for input files
fi

if [ 'x' != 'x'$3 ]
then
#ext="."$3; # the extension to iterate over for input files
ext=$3; # the extension to iterate over for input files
else
ext=".gif"; # the extension to iterate over for input files
fi

name=$1; # output will be placed in a folder named this

if [ $2 ]
then
classname=$2"-sprite";
else
classname=$1"-sprite";
fi
css="$name/$classname.css";
html="$name/test.html";

rm -fr $name;
mkdir $name;
touch $css $html;

echo "Generating sprite file...";
#echo convert *$ext -append $name/$classname$ext;
echo executing: convert $ext -append $name/$classname$ext2;
convert $ext -append $name/$classname$ext2;

echo "Sprite complete! - Creating css & test output...";

echo -e "<html>\n<head>\n\t<link rel=\"stylesheet\" href=\"`basename $css`\" />\n</head>\n<body>\n\t<h1>Sprite test page</h1>\n" >> $html

echo -e ".$classname {\n\tbackground:url('$classname$ext2') no-repeat top left; display:inline-block;\n}" >> $css;
counter=0;
offset=0;
for file in $ext
do
width=`identify -format "%[fx:w]" "$file"`;
height=`identify -format "%[fx:h]" "$file"`;
#idname=`basename "$file" $ext`;
idname=`basename "$file" $ext2`;

clean=${idname// /-}
echo ".$classname#$clean {" >> $css;
echo -e "\tbackground-position:0 -${offset}px;" >> $css;
echo -e "\twidth: ${width}px;" >> $css;
echo -e "\theight: ${height}px;\n}" >> $css;

echo -e "<a href=\"#\" class=\"$classname\" id=\"$clean\"></a>\n" >> $html;

let offset+=$height;
let counter+=1;
echo -e "\t#$counter done";
done

echo -e "<h2>Full sprite:</h2>\n<img src=\"$classname$ext2\" border=1/>" >> $html;
echo -e "</body>\n</html>" >> $html;

echo -e "\nComplete! - $counter sprites created, css written & test page output. @russenreaktor";

else

echo -e "There should be at least 1 argument!\n\tbuildSprite.sh output_folder classname input_pattern"
echo -e "\n\tbuildSprite.sh folder1 test '*.png' png"

fi

Source: jaymz.eu

No comments:

Post a Comment