Posted 26 days ago. Visible to the public.

ImageMagick: Converting SVG to PNG

Conversion

ImageMagick can convert SVGs to PNG.

Copy
convert input.svg output.png

If the SVG has a size of 24x24 (viewbox="0 0 24 24"), the resulting PNG will also have a size of 24x24.

Conversion with resizing (poor results)

If you want the PNG in a larger size, the naive approach would be to use the resize flag.

Copy
convert -resize 96x96 input.svg output.png

However, this results in a PNG with a rather poor resolution, as the resize conversion does not automatically scale the SVG.

Correlation of size and density

What you need in this case is the density flag to rescale the SVG. By default ImageMagick rasters SVGs with a density of 72 dpi. Increasing the density scales the SVG and results in a larger image size.
To get a PNG of the size 96x96 (4 times the size of the original size of the SVG) as in the example above, you need to set the density to 72 * 4

Copy
convert -density 288 input.svg output.png

This will give you a 96x96 PNG with a decent resolution (72 dpi). However, in my experience the result is better, if you set the density to a higher value and then resize to the desired size. But you can just toy with those values and see what works best for you.

Copy
convert -density 1200 -resize 96x96 input.svg output.png

Extra

You probably also want to set the background flag to 'none', to get a PNG with a transparent background

Copy
convert -density 1200 -background none -resize 96x96 input.svg output.png

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Bruno Sedler
Last edit:
26 days ago
by Bruno Sedler
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Bruno Sedler to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more