【问题标题】:python pptx add image without image filepython pptx添加没有图像文件的图像
【发布时间】:2016-10-20 07:32:16
【问题描述】:

我使用python pptx包(python 2.7)创建了一个pptx文件

我在内存中有一个图像,我使用 matplotlib 和以下代码创建:

import matplotlib.pyplot as plt

plt.clf()

plt.imshow(data, cmap='hot', interpolation='nearest')
plt.xlabel(x_l)
plt.ylabel(y_l)
plt.title(title)

x_values = range(len(times))

plt.xticks(x_values[::len(x_values)/24], range(24))

plt.yticks(range(len(dates)),dates)
plt.axes().set_aspect('auto')

return plt.gcf()

稍后我尝试使用

将此图像添加到 pptx 文件中
pic = shapes.add_picture(image, left,top = top, width= width, height = height )

并得到以下错误: AttributeError:“Figure”对象没有“read”属性

如果我将图像保存到文件中,然后使用完全相同的代码将其读取到具有路径的 pptx 文件中,则该代码有效。 adding image file to pptx file

我只找到了如何将图像文件添加到 pptx,而没有找到从内存中添加图像的方法。

我需要添加它而不将任何文件保存到磁盘。

谢谢!

【问题讨论】:

    标签: python python-2.7 python-pptx


    【解决方案1】:

    您可以将其保存到内存中的 StringIO 流(“类文件对象”)并将 StringIO 对象提供给 python-pptx。

    import StringIO
    
    image_stream = StringIO.StringIO()
    image.save(image_stream)
    pic = shapes.add_picture(image_stream, left, top, width, height)
    image_stream.close() # probably optional, but couldn't hurt
    

    另外两个问题有更多细节。

    【讨论】:

    • 能否请您详细说明答案,以便我能够接受?
    • @captainshai 我添加了更明确的代码 sn-p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    相关资源
    最近更新 更多