Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[python]python svg to png #15

Open
dounai1306 opened this issue Feb 9, 2017 · 0 comments
Open

[python]python svg to png #15

dounai1306 opened this issue Feb 9, 2017 · 0 comments

Comments

@dounai1306
Copy link
Owner

cairoSVG

官网:http://cairosvg.org/

介绍:
a SVG 1.1 to PNG, PDF, PS and SVG converter;
a command-line interface;
a Python 3.4+ library;
known to work at least on Linux, OS X, and Windows;
based on the Cairo 2D graphics library;
tested using the W3C test suite;
LGPLv3-licensed free software.

cairoSVG由于是根据svg代码生成,所以在美观上会比python pycha好看很多。

安装

pip install cairosvg

安装过程参考这里

windowns下安装,反复提示AttributeError: 'module' object has no attribute 'ANTIALIAS_FAST'。多次尝试后,安装步骤如下:

1、python版本可以2.x或者3.x

2、pip install lxml

3、pip install cairosvg

4、pip install cairocffi(如果这步有误,可尝试pip install cairocffi==0.6指定版本)

5、pip install pycairo(豆瓣貌似没有此源)

如果以上5步后,还没有成功,需要进行第6步

6、最后一步,安装GTK2,这步。相关资料

下载地址:GTK2 / GTK3

重启pycharm后,就可以正常使用了

使用

cairoSVG 提供了4个函数:

  • svg2pdf
  • svg2png
  • svg2ps
  • svg2svg

官方的栗子:

cairosvg.svg2png(url="/path/to/input.svg", write_to="/tmp/output.png")

cairosvg.svg2pdf(file_obj=open("/path/to/input.svg", "rb"), write_to="/tmp/output.pdf")

cairosvg.svg2ps(bytestring=open("/path/to/input.svg").read().encode('utf-8'))

我们实际的需求,是人工生成,所以直接将前台传递过来的svg代码转换为图片,具体代码如下:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import cairosvg
event_status = """
<svg xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" style="font-family:microsoft yahei;font-size:12px;" xmlns="http://www.w3.org/2000/svg" width="600" height="400">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:1;stroke:rgb(0,0,0)"/>
</svg>
"""
cairosvg.svg2png(bytestring=event_status, write_to='test.png')

小提示:cairosvg在转数据量较大的代码时,会变得很慢,所以一定要对数据进行一定取舍。

参考文章:

Installing cairo on Windows

AttributeError: 'module' object has no attribute 'ANTIALIAS_FAST'

@dounai1306 dounai1306 changed the title python svg to png [python]python svg to png Mar 10, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant