Convert Svg to Png in Python

Convert SVG to PNG in Python

The answer is "pyrsvg" - a Python binding for librsvg.

There is an Ubuntu python-rsvg package providing it. Searching Google for its name is poor because its source code seems to be contained inside the "gnome-python-desktop" Gnome project GIT repository.

I made a minimalist "hello world" that renders SVG to a cairo
surface and writes it to disk:

import cairo
import rsvg

img = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640,480)

ctx = cairo.Context(img)

## handle = rsvg.Handle(<svg filename>)
# or, for in memory SVG data:
handle= rsvg.Handle(None, str(<svg data>))

handle.render_cairo(ctx)

img.write_to_png("svg.png")

Update: as of 2014 the needed package for Fedora Linux distribution is: gnome-python2-rsvg. The above snippet listing still works as-is.

How to render SVG image to PNG file in Python?

there are multiple solutions available for converting svgs to pngs in python, but not all of them will work for your particular use case since you're working with svg filters.





































solutionfilter works?alpha channel?call directly from python?
cairosvgsome*yesyes
svglibnonoyes
inkscapeyesyesvia subprocess
wandyesyesyes

Convert a SVG to PNG using python?

You can use the library pyvips

And use it like this:

import pyvips

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

Convert SVG to PNG with Python on Windows

From the comments, the solution was to install svglib version 1.0.1 and reportlab 3.5.59.

Convert SVG image to PNG image by python

try using cairosvg

from cairosvg import svg2png

svg_code = """
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="8" x2="12" y2="12"/>
<line x1="12" y1="16" x2="12" y2="16"/>
</svg>
"""

svg2png(bytestring=svg_code,write_to='output.png')

answer by JWL

Convert SVG to png or other?

SVG are vectors images (the drawings are saved as commands to draw lines, circles, etc). PNGs are bitmaps. So to convert SVG to PNG, you need a renderer.

The most obvious solution is ImageMagick, a library you have already installed, as it is used in several programs. A less obvious approach is using Inkscape. Using the commandline options, it's possible to use Inkscape as a conversion program. As Inkscape is vector oriented, I suspect quality to be better than ImageMagick (which is more bitmap-minded).

As a vector image (SVG) is a text file containing drawing instructions, it's easier to understand. PNGs contain just pixel information, and, to make things worse, they are compressed with a fairly complicated algorithm. Making sense of them is not as easy.

Have a look at the Inkscape man page, it's fairly obvious how to use it. This is the IMagick convert help.



Related Topics



Leave a reply



Submit