How to convert SVG to PNG or JPEG in Python?

hkm picture hkm · Jul 20, 2018 · Viewed 14k times · Source

I'm using svgwrite and generating svg-files, how do I convert them to PNG or JPEG?

Answer

jcupitt picture jcupitt · Jul 13, 2020

pyvips supports SVG load. It's free, fast, needs little memory, and works on macOS, Windows and Linux.

You can use it like this:

import pyvips

image = pyvips.Image.new_from_file("something.svg", dpi=300)
image.write_to_file("x.png")

The default DPI is 72, which might be a little low, but you can set any DPI you like. You can write to JPG instead in the obvious way.

You can also load by the pixel dimensions you want like this:

import pyvips

image = pyvips.Image.thumbnail("something.svg", 200, height=300)
image.write_to_file("x.png")

That will render the SVG to fit within a 200 x 300 pixel box. The docs introduce all the options.

The pyvips SVG loader has some nice properties:

  • It uses librsvg for the actual rendering, so the PNG will have high-quality anti-aliased edges.
  • It's much faster than systems like ImageMagick, which simply shell out to inkscape for rendering.
  • It supports progressive rendering. Large images (more than a few thousand pixels a side) are rendered in sections, keeping memory use under control, even for very large images.
  • It supports streaming, so you can render an SVG directly to a huge Deep Zoom pyramid (for example) without needing any intermediate storage.
  • It supports input from memory areas, strings and pipes as well as files.

Rendering from strings can be handy, eg.:

import pyvips

x = pyvips.Image.svgload_buffer(b"""
<svg viewBox="0 0 200 200">
  <circle r="100" cx="100" cy="100" fill="#900"/>
</svg>
""")

x.write_to_file("x.png")