在 Python 中将 SVG 转换为 PNG [英] Convert SVG to PNG in Python
问题描述
如何在 Python 中将 svg
转换为 png
?我将 svg
存储在 StringIO
的实例中.我应该使用 pyCairo 库吗?我该如何编写该代码?
答案是pyrsvg" - librsvg 的 Python 绑定.>
有一个 Ubuntu python-rsvg 包提供它.在 Google 上搜索它的名字很糟糕,因为它的源代码似乎包含在gnome-python-desktop"Gnome 项目 GIT 存储库中.
我制作了一个极简主义的hello world",将 SVG 渲染为 cairo表面并将其写入磁盘:
导入开罗导入 rsvgimg = cairo.ImageSurface(cairo.FORMAT_ARGB32, 640,480)ctx = cairo.Context(img)## handle = rsvg.Handle(
更新:截至 2014 年,Fedora Linux 发行版所需的软件包是:gnome-python2-rsvg
.上面的代码片段列表仍然按原样工作.
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?
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.
这篇关于在 Python 中将 SVG 转换为 PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!