在Python中将SVG转换为PNG [英] Convert SVG to PNG in Python

查看:946
本文介绍了在Python中将SVG转换为PNG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中将svg转换为png?我将svg存储在StringIO的实例中.我应该使用pyCairo库吗?我该如何编写代码?

解决方案

答案是" pyrsvg "-用于 librsvg 的Python绑定.. >

有一个Ubuntu python-rsvg软件包.在Google上搜索它的名字很糟糕,因为它的源代码似乎包含在"gnome-python-desktop" Gnome项目GIT存储库中.

我制作了一个极简主义的"hello world",将SVG渲染为开罗 表面并将其写入磁盘:

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")

更新:从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆