1

Currently I am trying to plot my DataFrame data and add to my pptx slide. I used matplotlib + pptx-python to do the work. In the process, I tried to save the plot image to io in-memory stream and use it for pptx slide. The steps are:

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)

But I got an error like this:

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

Do you know how to solve this problem? BTW I am using Python 3.6. I tried to update PIL package and use 'png' and 'jpg' formats for my image. All efforts didn't work.

FunkyMore
  • 223
  • 1
  • 2
  • 8

1 Answers1

0

Don't use PIL to open the .png file before giving it to .add_picture():

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)

The .add_picture() method is looking for a file-like object containing an image, which is buf in this case. When you called Image.open() with buf you get a PIL image object of some sort, which is not what you need.

scanny
  • 26,423
  • 5
  • 54
  • 80