Please join me at my new location

Sunday, February 13, 2011

Scripting Inkscape


$INKSCAPE/Contents/Resources/bin/inkscape in.svg -e out.png -D -h 100 -w 100

SVGs, like all other vector graphics formats are scalable and work well for any sort of graphic that needs to scale well to different resolutions. So if you have an image that needs to displayed at many different sizes vector graphics are a good bet.

Vector graphics take much more overhead to render than do raster images. Since raster graphics are simply an array of bytes in memory that represent each pixel of the image they are relatively simple for a computer to perform operations on. Vector graphics on the other hand are usually stored as a series of drawing operations: draw a rectangle, fill it with a gradient, clip it with circle, etc. Because these operations have to be executed in order, sometimes drawing over the same pixels a few times they can be slower. Hence, vector graphics applications, such as Inkscape, have a rasterizer in them that takes the output of the SVG and converts it into a raster image. You might think of a vector graphic as a recipe, or the source code, for a raster graphic.

Using Inkscape to rasterize images can be a chore since you have to open manually adjust the size of the output graphic and filename for each different size that you want to generate. Luckily inkscape includes a command line rasterizer that you can script!

On the Mac, the actual executable is within the bundle in Contents/Resources/bin/inkscape. You can invoke it from the terminal with options to control the height and width of the output graphic, it's name as well as a few other options. Running inkscape --help will list all of the available options. The ones we're concerned with are: -e, -C/-D, -h, and -w. -C is used when you want to export the drawing and -D when you want to export the entire page. The difference between the two being that exporting the page will export everything including white space around your drawing and exporting the drawing will trigger Inkscape to find the smallest rectangle that includes everything you've drawn (which might be smaller than the page) and export that.

To export the drawing contained in "Scenery.svg" to a 100x100 PNG called "Scenery.png" you would use the following command in Terminal:

$INKSCAPE/Contents/Resources/bin/inkscape Scenery.svg -e Scenery.png -D -h 100 -w 100

Where $INKSCAPE-APP is the location of

Since rasterizing SVGs is something you might be doing frequently you can always write a script to run the above command with different sizes and output names. If you want to get fancy you could even automate the process using Make or another build tool.