如何在python中将图像的URI转换为图像文件

时间:2018-01-06 02:53:53

标签: python image uri pillow pygal

我的程序使用pygal创建一个简单的图表,并将图表输出为URI字符串。我想将这个URI转换成一个我可以用枕头操作的图像。我已经尝试解码字符串但无法使其工作。我的代码的当前版本接受URI并将其转换为字节,因为我希望这会使转换更容易,如果我不需要这样做,我可以删除该行。

#Pygal graphing test

import pygal

import base64

from PIL import Image

#Get number of loops needed
user_num = int(input("How many people are taking the survey?"))
print()

#Give values to colour variables
red = 0
orange = 0
yellow = 0
green = 0
blue = 0
purple = 0


#Loop getting data from user
for x in range(1,user_num + 1):

    user_colour = input("What is your favourite colour?")
    print()

    if user_colour == "red":
        red = red + 1

    elif user_colour == "orange":
        orange = orange + 1

    elif user_colour == "yellow":
        yellow = yellow + 1

    elif user_colour == "green":
        green = green + 1

    elif user_colour == "blue":
        blue = blue + 1

    elif user_colour == "purple":
        purple = purple + 1

#Create bar graph object
bar_chart = pygal.Bar()

#Title of graph
bar_chart.title = "Favourite Colour"

#X-Axis label
bar_chart.x_labels = ("Red", "Orange", "Yellow", "Green", "Blue", "Purple")

#Add values
bar_chart.add('Favourite Colours', [red,orange,yellow,green,blue,purple])

#Save chart
data = bar_chart.render_data_uri()

#Convert string to bytes
b = bytes(data, 'utf-8')

1 个答案:

答案 0 :(得分:0)

我无法让PIL.Image读取数据,因为您生成的图像似乎是SV​​G图像而PIL不支持它。您可以查看原因background music section here

为了按照here所述将SVG转换为PNG,我们可以使用cairosvg

import base64
import io
from PIL import Image
import pygal
from cairosvg import svg2png

# ... your code

# Save chart
data = bar_chart.render_data_uri()

# Remove the header placed by the URI
data = data.replace('data:image/svg+xml;charset=utf-8;base64,', '')

# Convert to bytes
data = data.encode()

# The data is encoded as base64, so we decode it.
data = base64.b64decode(data)

# Open a bytes file object
with io.BytesIO() as f:
    # write the svg data as a png to file object
    svg2png(bytestring=data, write_to=f)

    # read the file object with PIL and display
    img = Image.open(f)
    img.show()

<强>更新

我建议使用Anaconda在环境中安装cairosvg。这就是我创建环境和安装依赖项所做的。

$ conda create -n test python=3.5
$ source activate test
$ conda install --channel-priority -c conda-forge cairosvg
$ pip install pygal
$ python graph_testing.py  # run code