我正在尝试从剪贴板中获取图像,我想在python-pptx中添加该图像。 我不想将图像保存在磁盘中。 我试过这个:
from pptx import Presentation
from PIL import ImageGrab,Image
from pptx.util import Inches
im = ImageGrab.grabclipboard()
prs = Presentation()
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
left = top = Inches(1)
pic = slide.shapes.add_picture(im, left, top)
prs.save('PPT.pptx')
但是得到这个错误
File "C:\Python27\lib\site-packages\PIL\Image.py", line 627, in __getattr__
raise AttributeError(name)
AttributeError: read
这有什么问题?
答案 0 :(得分:0)
图像需要采用流(即逻辑文件)对象的形式。所以你需要先将它“保存”到一个内存文件中,可能是你正在寻找的StringIO。
This other question提供了一些细节。
答案 1 :(得分:0)
这对我有用
import io
import PIL
from pptx import Presentation
from pptx.util import Inches
# already have a PIL.Image as image
prs = Presentation()
blank_slide = prs.slide_layout[6]
left = top = Inches(0)
# I had this part in a loop so that I could put one generated image per slide
image: PIL.Image = MyFunctionToGetImage()
slide = prs.slides.add_slide(blank_slide)
with io.BytesIO() as output:
image.save(output, format="GIF")
pic = slides.add_slide(output, left, top)
# end loop
prs.save("my.pptx")