[svg] How to convert a SVG to a PNG with ImageMagick?

I have a SVG file that has a defined size of 16x16. When I use ImageMagick's convert program to convert it into a PNG, then I get a 16x16 pixel PNG which is way too small:

convert test.svg test.png

I need to specify the pixel size of the output PNG. -size parameter seems to be ignored, -scale parameter scales the PNG after it has been converted to PNG. The best result up to now I got by using the -density parameter:

convert -density 1200 test.svg test.png

But I'm not satisfied, because I want to specify the output size in pixels without doing math to calculate the density value. So I want to do something like this:

convert -setTheOutputSizeOfThePng 1024x1024 test.svg test.png

So what is the magic parameter I have to use here?

This question is related to svg imagemagick png

The answer is


I haven't been able to get good results from ImageMagick in this instance, but Inkscape does a nice job of scaling an SVG on Linux and Windows:

inkscape -z -w 1024 -h 1024 input.svg -e output.png

Note that you can omit one of the width/height parameters to have the other parameter scaled automatically based on the input image dimensions.

Edit (May 2020): Inkscape 1.0 users, please note that the command line arguments have changed:

inkscape -w 1024 -h 1024 input.svg -o output.png

Here's the result of scaling a 16x16 SVG to a 200x200 PNG using this command:

enter image description here

enter image description here

Just for reference, my Inkscape version (on Ubuntu 12.04) is:

Inkscape 0.48.3.1 r9886 (Mar 29 2012)

and on Windows 7, it is:

Inkscape 0.48.4 r9939 (Dec 17 2012)

On Linux with Inkscape 1.0 to convert from svg to png need to use

inkscape -w 1024 -h 1024 input.svg --export-file output.png

not

inkscape -w 1024 -h 1024 input.svg --export-filename output.png

This is what worked for me

find . -type f -name "*.svg" -exec bash -c 'rsvg-convert -h 1000  $0 > $0.png' {} \;
rename 's/svg\.png/png/' *

This will loop all the files in your current folder and sub folder and look for .svg files and will convert it to png with transparent background.

Make sure you have installed the librsvg and rename util

brew install librsvg
brew install rename

On macOS using brew, using librsvg directly works well

brew install librsvg
rsvg-convert test.svg -o test.png

Many options are available via rsvg-convert --help


Without librsvg, you may get a black png/jpeg image. We have to install librsvg to convert svg file with imagemagick.

Ubuntu

 sudo apt-get install imagemagick librsvg
 convert -density 1200 test.svg test.png

MacOS

 brew install imagemagick librsvg
 convert -density 1200 test.svg test.png


Try svgexport:

svgexport input.svg output.png 64x
svgexport input.svg output.png 1024:1024

svgexport is a simple cross-platform command line tool that I have made for exporting svg files to jpg and png, see here for more options. To install svgexport install npm, then run:

npm install svgexport -g

Edit: If you find an issue with the library, please submit it on GitHub, thanks!


I've solved this issue through changing the width and height attributes of the <svg> tag to match my intended output size and then converting it using ImageMagick. Works like a charm.

Here's my Python code, a function that will return the JPG file's content:

import gzip, re, os
from ynlib.files import ReadFromFile, WriteToFile
from ynlib.system import Execute
from xml.dom.minidom import parse, parseString


def SVGToJPGInMemory(svgPath, newWidth, backgroundColor):

    tempPath = os.path.join(self.rootFolder, 'data')
    fileNameRoot = 'temp_' + str(image.getID())

    if svgPath.lower().endswith('svgz'):
        svg = gzip.open(svgPath, 'rb').read()
    else:
        svg = ReadFromFile(svgPath)

    xmldoc = parseString(svg)

    width = float(xmldoc.getElementsByTagName("svg")[0].attributes['width'].value.split('px')[0])
    height = float(xmldoc.getElementsByTagName("svg")[0].attributes['height'].value.split('px')[0])

    newHeight = int(newWidth / width * height) 

    xmldoc.getElementsByTagName("svg")[0].attributes['width'].value = '%spx' % newWidth
    xmldoc.getElementsByTagName("svg")[0].attributes['height'].value = '%spx' % newHeight

    WriteToFile(os.path.join(tempPath, fileNameRoot + '.svg'), xmldoc.toxml())
    Execute('convert -background "%s" %s %s' % (backgroundColor, os.path.join(tempPath, fileNameRoot + '.svg'), os.path.join(tempPath, fileNameRoot + '.jpg')))

    jpg = open(os.path.join(tempPath, fileNameRoot + '.jpg'), 'rb').read()

    os.remove(os.path.join(tempPath, fileNameRoot + '.jpg'))
    os.remove(os.path.join(tempPath, fileNameRoot + '.svg'))

    return jpg

In ImageMagick, one gets a better SVG rendering if one uses Inkscape or RSVG with ImageMagick than its own internal MSVG/XML rendered. RSVG is a delegate that needs to be installed with ImageMagick. If Inkscape is installed on the system, ImageMagick will use it automatically. I use Inkscape in ImageMagick below.

There is no "magic" parameter that will do what you want.

But, one can compute very simply the exact density needed to render the output.

Here is a small 50x50 button when rendered at the default density of 96:

convert button.svg button1.png


enter image description here

Suppose we want the output to be 500. The input is 50 at default density of 96 (older versions of Inkscape may be using 92). So you can compute the needed density in proportion to the ratios of the dimensions and the densities.

512/50 = X/96
X = 96*512/50 = 983


convert -density 983 button.svg button2.png


enter image description here

In ImageMagick 7, you can do the computation in-line as follows:

magick -density "%[fx:96*512/50]" button.svg button3.png

or

in_size=50
in_density=96
out_size=512

magick -density "%[fx:$in_density*$out_size/$in_size]" button.svg button3.png

why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:

FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"


This is not perfect but it does the job.

convert -density 1200 -resize 200x200 source.svg target.png

Basically it increases the DPI high enough (just use an educated/safe guess) that resizing is done with adequate quality. I was trying to find a proper solution to this but after a while decided this was good enough for my current need.

Note: Use 200x200! to force the given resolution


For simple SVG to PNG conversion I found cairosvg (https://cairosvg.org/) performs better than ImageMagick. Steps for install and running on all SVG files in your directory.

pip3 install cairosvg

Open a python shell in the directory which contains your .svg files and run:

import os
import cairosvg

for file in os.listdir('.'):
    name = file.split('.svg')[0]
    cairosvg.svg2png(url=name+'.svg',write_to=name+'.png') 

This will also ensure you don't overwrite your original .svg files, but will keep the same name. You can then move all your .png files to another directory with:

$ mv *.png [new directory]

If you are on MacOS X and having problems with Imagemagick's convert, you might try reinstalling it with RSVG lib. Using HomeBrew:

brew remove imagemagick
brew install imagemagick --with-librsvg

Verify that it's delegating correctly:

$ convert -version
Version: ImageMagick 6.8.9-8 Q16 x86_64 2014-12-17 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2014 ImageMagick Studio LLC
Features: DPC Modules
Delegates: bzlib cairo fontconfig freetype jng jpeg lcms ltdl lzma png rsvg tiff xml zlib

It should display rsvg.


I came to this post - but I just wanted to do the conversion by batch and quick without the usage of any parameters (due to several files with different sizes).

rsvg drawing.svg drawing.png

For me the requirements were probably a bit easier than for the original author. (Wanted to use SVGs in MS PowerPoint, but it doesn't allow)


Inkscape doesn't seem to work when svg units are not px (e.g. cm). I got a blank image. Maybe, it could be fixed by twiddling the dpi, but it was too troublesome.

Svgexport is a node.js program and so not generally useful.

Imagemagick's convert works ok with:

 ~$ convert -background none -size 1024x1024 infile.svg outfile.png

If you use -resize, the image is fuzzy and the file is much larger.

BEST

~$ rsvg  -w 1024 -h 1024 infile.svg  outfile.png

It is fastest, has the fewest dependencies, and the output is about 30% smaller than convert. Install librsvg2-bin to get it. There does not appear to be a man page but you can type:

~$ rsvg --help

to get some assistance. Simple is good.


One thing that just bit me was setting the -density AFTER the input file name. That didn't work. Moving it to the first option in convert (before anything else) made it work (for me, YMMV, etc).


In order to rescale the image, the option -density should be used. As far as I know the standard density is 72 and maps the size 1:1. If you want the output png to be twice as big as the original svg, set the density to 72*2=144:

convert -density 144 source.svg target.png

The top answer by @808sound did not work for me. I wanted to resize Kenney.nl UI Pack

and got Kenney UI Pack messed up

So instead I opened up Inkscape, then went to File, Export as PNG fileand a GUI box popped up that allowed me to set the exact dimensions I needed.

Version on Ubuntu 16.04 Linux: Inkscape 0.91 (September 2016)

(This image is from Kenney.nl's asset packs by the way)


After following the steps in Jose Alban's answer, I was able to get ImageMagick to work just fine using the following command:

convert -density 1536 -background none -resize 100x100 input.svg output-100.png

The number 1536 comes from a ballpark estimate of density, see this answer for more information.


Examples related to svg

How to extract svg as file from web page How to display svg icons(.svg files) in UI using React Component? Why don’t my SVG images scale using the CSS "width" property? How to show SVG file on React Native? Easiest way to use SVG in Android? IE11 meta element Breaks SVG img src SVG changing the styles with CSS How to use SVG markers in Google Maps API v3 Embedding SVG into ReactJS How to change the color of an svg element?

Examples related to imagemagick

ImageMagick security policy 'PDF' blocking conversion convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453 How to convert a SVG to a PNG with ImageMagick? Storing image in database directly or as base64 data? Set transparent background using ImageMagick and commandline prompt How to convert a .eps file to a high quality 1024x1024 .jpg? Recommendation for compressing JPG files with ImageMagick Convert PDF to image with high resolution rmagick gem install "Can't find Magick-config" Convert SVG image to PNG with PHP

Examples related to png

Convert UIImage to NSData and convert back to UIImage in Swift? Importing PNG files into Numpy? What is difference between png8 and png24 How to change the background colour's opacity in CSS Darkening an image with CSS (In any shape) Android splash screen image sizes to fit all devices How to convert a SVG to a PNG with ImageMagick? Convert RGBA PNG to RGB with PIL Set transparent background using ImageMagick and commandline prompt Converting a byte array to PNG/JPG