Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert SVG to PNG or JPEG in Python?

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

like image 863
hkm Avatar asked Jul 20 '18 20:07

hkm


People also ask

How do I convert SVG to PNG?

Navigate to an . svg file, right click on it and click on the context menu item 'Save SVG as PNG. Lets you click on the extension icon or right click on an . svg file and choose Save SVG as PNG.

Does Python support SVG?

Svglib is a pure-Python library for reading SVG files and converting them (to a reasonable degree) to other formats using the ReportLab Open Source toolkit.


1 Answers

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")
like image 98
jcupitt Avatar answered Sep 17 '22 14:09

jcupitt