How do I convert an svg
to png
, in Python? I am storing the svg
in an instance of StringIO
. Should I use the pyCairo library? How do I write that code?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
A little extension on the answer of jsbueno:
Install Inkscape and call it as command line:
You can also snap specific rectangular area only using parameter
-j
, e.g. co-ordinate "0:125:451:217"If you want to show only one object in the SVG file, you can specify the parameter
-i
with the object id that you have setup in the SVG. It hides everything else.Another solution I've just found here How to render a scaled SVG to a QImage?
PySide is easily installed from a binary package in Windows (and I use it for other things so is easy for me).
However, I noticed a few problems when converting country flags from Wikimedia, so perhaps not the most robust svg parser/renderer.
Here is an end-to-end Python example.
Note that it suppresses certain crufty output that Inkscape writes to the console (specifically, stderr and stdout) during normal error-free operation. The output is captured in two string variables,
out
anderr
.For example, when running a particular job on my Mac OS system,
out
ended up being:(The input svg file had a size of 339 by 339 pixels.)
SVG scaling and PNG rendering
Using pycairo and librsvg I was able to achieve SVG scaling and rendering to a bitmap. Assuming your SVG is not exactly 256x256 pixels, the desired output, you can read in the SVG to a Cairo context using rsvg and then scale it and write to a PNG.
main.py
RSVG C binding
From the Cario website with some minor modification. Also a good example of how to call a C-library from 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:
Update: as of 2014 the needed package for Fedora Linux distribution is:
gnome-python2-rsvg
. The above snippet listing still works as-is.