Sunday, July 18, 2010

Exporting slices from Inkscape

If you have a Python interpreter available, you can use the slightly better alternative from Part 2.

In Photoshop, it's possible to “slice” an image into pieces, name the individual pieces, and export each to a separate file. This is really useful for web design: you can do the whole design in one image, then export the bits and pieces for later reassembling in HTML/CSS. Can we do the same slicing trick with Inkscape?

It turns out that we can; it's even on the Inkscape Tips and Tricks page. However, the exporting itself remains manual labour. I wrote a bash script to automate that; the code is given below.

The process is as follows:

  • First, draw your image as usual.
  • Then, add a layer that will hold the slices; name it, for example, slices. Set the layer's opacity to about 50% to be able to see what you're doing. Enable the grid, and make sure it is set to pixels: you want your slices to align with pixel boundaries.
  • Draw your slice rectangles onto the slices layer, aligned to the grid. Ensure that the rectangles have no border; the fill is irrelevant (I use red).
  • Right-click a slice, and choose Object Properties. Change Id field to EXP-something and hit Enter. The tag EXP- indicates that this rectangle is intended for export; something will become the filename (something.png). Repeat this for all slices.
  • Hide the slices layer, and save your image. Let's say you called it layout.svg.
  • Run the script as follows:
    ./ layout.svg
    You should see each of your slices being exported to a PNG file in the same directory.

Here's the code for the script. Save this to a file and make it executable.


if [[ -z $1 ]] ; then
 echo "Usage: $0 [FILE]"
 exit 0


for ID in `grep -o "id=\"$PREFIX.*\"" $FILENAME | cut -d\" -f2` ; do
 echo "Exporting area $ID to $OUTPUT..."
 inkscape --export-id=$ID --export-png=$OUTPUT --file=$FILENAME