1

我正在尝试使用 matplotlib 创建一些图形,然后使用 python-pptx 将它们保存到 ppt 文件,而不将图像文件保存到磁盘。

如果我看到python-pptx 的文档,我可以看到它add_picture()接受像对象这样的文件,但我仍然收到此错误:

  File "a.py", line 39, in <module>
    pic = slide.shapes.add_picture(image_stream, left, top)
  File "/usr/local/lib/python2.7/dist-packages/pptx/shapes/shapetree.py", line 496, in add_picture
    image_part, rId = self.part.get_or_add_image_part(image_file)
  File "/usr/local/lib/python2.7/dist-packages/pptx/parts/slide.py", line 42, in get_or_add_image_part
    image_part = self._package.get_or_add_image_part(image_file)
  File "/usr/local/lib/python2.7/dist-packages/pptx/package.py", line 50, in get_or_add_image_part
    return self._image_parts.get_or_add_image_part(image_file)
  File "/usr/local/lib/python2.7/dist-packages/pptx/package.py", line 161, in get_or_add_image_part
    image_part = ImagePart.new(self._package, image)
  File "/usr/local/lib/python2.7/dist-packages/pptx/parts/image.py", line 44, in new
    partname = package.next_image_partname(image.ext)
  File "/usr/local/lib/python2.7/dist-packages/pptx/util.py", line 136, in get_prop_value
    value = f(obj)
  File "/usr/local/lib/python2.7/dist-packages/pptx/parts/image.py", line 238, in ext
    format = self._format
  File "/usr/local/lib/python2.7/dist-packages/pptx/parts/image.py", line 273, in _format
    return self._pil_props[0]
  File "/usr/local/lib/python2.7/dist-packages/pptx/util.py", line 136, in get_prop_value
    value = f(obj)
  File "/usr/local/lib/python2.7/dist-packages/pptx/parts/image.py", line 282, in _pil_props
    pil_image = PIL_Image.open(stream)
  File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 2572, in open
    % (filename if filename else fp))
IOError: cannot identify image file <StringIO.StringIO instance at 0x7f30d72a92d8>

这是我下面的代码:

import matplotlib.pyplot as plt

from StringIO import StringIO


from pptx import Presentation
from pptx.util import Inches


image_stream = StringIO()


# plot a simple graph
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.ylabel('some numbers')

# saving image file from matplotlib to memory
plt.savefig(image_stream)



prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
title = slide.shapes.title
subtitle = slide.placeholders[1]

left = top = Inches(1)

## this line throws error, but why ????????
pic = slide.shapes.add_picture(image_stream, left, top)


prs.save('test.pptx')

我错过了什么?

4

1 回答 1

2

您需要将 StringIO 对象的光标重新定位到“文件”的开头,然后再将其发送到.add_picture()

image_stream.seek(0)
picture = slide.shapes.add_picture(image_stream, left, top)

写操作将光标留在文件末尾(准备好进行其他写操作)。但是,.add_picture()代码只能调用.read()以获取内容(.seek()并非对所有类似文件的对象都可用),因此您必须在调用之前重新定位光标。

于 2017-11-01T17:14:52.023 回答