Convert and resize SVG to PNG

DJL picture DJL · Aug 12, 2013 · Viewed 25.9k times · Source

I am trying to convert SVG to PNG (or any raster format) and resize at the same time.

I thought I would use ImageMagick for this task but it seems to be converting to raster before resizing.

This results in a poor quality image.

  • Is there a way to get ImageMagick to resize the SVG before converting to raster?

  • Or is there some other tool I can use to programatically convert an SVG to a raster after resizing it?

  • Alternatively, is there some other tool I could use for this?

Currently I'm using ImageMagick via a commandline:

convert file.svg -resize 100x100 file.png

The source image "size" is unknown and the destination size is not known until run-time.

Answer

Tony Bogdanov picture Tony Bogdanov · Feb 18, 2016

This is the way I do it and it seems to work.

convert -background none -density 1000 -resize 1000x compass.svg compass.png

Here's what each part does.

  • Use -background none to make sure any transparent parts of the SVG stay transparent and not get filled with white.
  • As ImageMagick only works with raster images you need to use -density 1000 and specify the width to which you want to resize the SVG. This way when you actually call the resize command, the raster representation of the loaded SVG will already have a width of 1000, otherwise you'll end up resizing a raster up or down from whatever the original size of the SVG image is.
  • Now use -resize 1000x to give your SVG a new width, the height will be calculated automatically to keep the aspect ratio.

One pitfall of this, is that I don't really know how you could resize based on the height and let the width be calcualted since -density is applied to the width, not the height. So, you'd have to know the actual ratio of your SVG beforehand and work with the width accordingly.