Last Updated: September 09, 2019
·
2.77K
· richthegeek

SVG to PNG in multiple sizes and colors

I needed to use an icon set (Entypo) that was only provided itself as SVG files, and I needed to have multiple sizes and colors available. So I wrote a script to convert them, with color name aliases!

A few notes on the implementation, to explain the slightly odd flow:
1. the colors have aliases (eg #33b5e3 is "holo")
2. everything is checked for existence first, so adding a color will only generate the files required (faster!)
3. it generates a large (1024x1024) version of the image, because colorization removes antialiasing. This is downscaled for supersampled antialiasing.

To use it, customise the sizes, colors, and aliases at the top of the script, add the +x flag, and run it in the folder containing the SVG files:

#!/bin/bash
sizes="16 24 32 64 128 256"
colors=("#000" "#33b5e3" "#808080")
names=("black" "holo" "grey")



count=${#names[@]}
for i in `seq 1 $count` ; do
    name=${names[i - 1]}
    if [ ! -d pngs/$name ] ; then
        mkdir pngs/$name
    fi
    for size in $sizes ; do
        if [ ! -d pngs/$name/$size ] ; then
            mkdir pngs/$name/$size
        fi
    done
done

for svg in `ls *svg` ; do
    png=`echo $svg | sed s/.svg/.png/`

    for i in `seq 1 $count` ; do
        color=${colors[i - 1]}
        name=${names[i - 1]}

        big=pngs/$name/$png

        # export a massive one in this color...
        if [ ! -f $big ] ; then
            convert -depth 16 -background transparent -fill $color -colorize 100% -resize 1024x1024 $svg $big
        fi


        for size in $sizes ; do
            this=pngs/$name/$size/$png
            if [ ! -f $this ] ; then
                convert $big -resize $size"x"$size $this
            fi
        done

    done

    echo "Converted $svg > $png"

done

1 Response
Add your response

Hi Richard,

Thank you for this code, it looks like it fits perfectly for my need. However for now I don't understand how to use it :(

Does this trick has to be used with ImageMagick?

over 1 year ago ·