Read more

ImageMagick: Converting SVG to raster image formats like PNG or JPEG

Bruno Sedler
November 08, 2021Software engineer at makandra GmbH

Conversion

ImageMagick can convert SVGs to raster image formats.

Illustration money motivation

Opscomplete powered by makandra brand

Save money by migrating from AWS to our fully managed hosting in Germany.

  • Trusted by over 100 customers
  • Ready to use with Ruby, Node.js, PHP
  • Proactive management by operations experts
Read more Show archive.org snapshot

Example for PNG:

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.

Resizing

An SVG's viewBox specifies the intended size, but vector image formats can be scaled freely.

Resize flag (poor results)

If you want your raster image to be larger, the naive approach would be to use the resize flag.

convert -resize 96x96 input.svg output.png

However, this results in a blurred image, as the resize conversion does not actually scale the SVG but its raster interpretation.

Correlation of size and density

Instead, use 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 an image of the size 96x96 (4 times the SVG's size in our example), you need to set the density to 72 * 4.

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.

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

Transparency

By default, your target image is rendered with a white background. To keep an SVG's transparent background, set the background flag to 'none'.

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

Note

This only works for image formats which support transparency (like PNG, not JPEG).

See also

We have a separate card about converting SVG to other raster formats.

Hint

The tool from that card (CairoSVG) also support converting to PNG with perfectly crisp edges and transparency.

Posted by Bruno Sedler to makandra dev (2021-11-08 15:35)