Thursday, July 24, 2008

SVG to PNG

I wrote this little helper bash script when I was doing a logo in Inkscape. The problem is I never know what size of logo I want, or want multiple sizes, so I usually end up doing multiple exports, which is just too much clicking for me. So I did this simple script which will take a bunch of SVG files and turn them into a (much bigger) bunch of PNG files.

The script just sends multiple requests to convert the file to a utility called rsvg (which i got using `apt-get install librsvg2-bin`).The requests specify an output filename and the size (line 33). The output sizes can be set in the sizes array (line 15) - just put the sizes (in pixels) in the brackets separated by spaces.

Example, for a file called super-cool-logo.svg, if you specify the sizes array like this:

sizes=(10 100 1000)

the script will generate the following files:

  • super-cool-logo-10x10.png
  • super-cool-logo-100x100.png
  • super-cool-logo-1000x1000.png

Warning: If the files were already there, they will be overwritten

The drawback at the moment is that it creates square output! That is sufficient for me at the time, so I will patch it up when I get a need for it.

The script:
#!/bin/bash
#
# (Batch) SVG to PNG script.
# Converts an svg file into a number of png files of different sizes.
# The sizes can be specified in the sizes array (line 15).
#
# Potential issues:
#   This script will overwrite existing png files
# Parameters:
10#   at least one path of SVG file to convert
11# Requires:
12#   rsvg (http://librsvg.sourceforge.net/)
13# Author:
14#   Konrad Siek 
15
16# Array of sizes to convert to
17sizes=(16 32 64 128 256 512)
18
19# Check if any files were specified
20if [ $# -gt 0 ]; then
21    for svg_file in $@
22    do
23        # Check if file exists
24        if [ -f $svg_file ]
25        then
26            # Extract name of file (remove extension)
27            svg_name=$(echo $svg_file | cut -f 1 -d "." | tr -d " ")
28    
29            # Convert file to png with of the sizes
30            for s in $(seq 0 $((${#sizes[@]} - 1)))
31            do
32                size=${sizes[$s]}
33                rsvg -w $size -h $size $svg_file $svg_name-${size}x$size.png
34            done
35        else
36            # Warning message.
37            echo "$0: File $svg_file does not exist and will be ignored."
38        fi
39    done
40else
41    # Usage message.
42    echo "$0: Provide at least one SVG file to convert, please."
43fi


The code is also available at GitHub as bash/svg_to_png.