图像 Python IO 内存流保存和使用出错

Error with image Python IO in-memory stream save and use

目前我正在尝试绘制我的 DataFrame 数据并添加到我的 pptx 幻灯片中。我使用 matplotlib + pptx-python 来完成这项工作。在此过程中,我尝试将绘图图像保存到 io 内存流中,并将其用于 pptx 幻灯片。步骤是:

import io
from PIL import Image
from pptx import Presentation
from pptx.util import Inches

#1. Run Python-pptx and open presentation
prs = Presentation('Template.pptx')
title_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
title.text = 'FileName'
left = top = Inches(1) 

#2. plot the data in matplotlib
fig, ax = plt.subplots()
df.groupby('Name').plot(x='Time',y='Score', ax=ax)

#3. save the plot to io in-memory stream
buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)

#4. add image to slide 
pic = slide.shapes.add_picture(im, left, top)

但是我得到了这样的错误:

AttributeError: 'PngImageFile' object has no attribute 'read'

你知道如何解决这个问题吗?顺便说一句,我正在使用 Python 3.6。我尝试更新 PIL 包并为我的图像使用 'png' 和 'jpg' 格式。所有的努力都没有奏效。

在将 .png 文件提供给 .add_picture() 之前不要使用 PIL 打开它:

buf = io.BytesIO()
fig.savefig(buf, format='png')
buf.seek(0)
# ---skip the Image.open() step and feed buf directly to .add_picture()
pic = slide.shapes.add_picture(buf, left, top)

.add_picture() 方法正在查找包含图像的类文件对象,在本例中为 buf。当您使用 buf 调用 Image.open() 时,您会得到某种 PIL 图像对象,这不是您需要的。