How to pass PIL image to Add_Picture in python-pptx

无人久伴 提交于 2019-12-11 06:10:42

问题


I'm trying to get the image from clipboard and I want to add that image in python-pptx . I don't want to save the image in the Disk. I have tried this:

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')

But Getting this error

File "C:\Python27\lib\site-packages\PIL\Image.py", line 627, in __getattr__
    raise AttributeError(name)
AttributeError: read

What is wrong with this?


回答1:


The image needs to be in the form of a stream (i.e. logical file) object. So you need to "save" it to a memory file first, probably StringIO is what you're looking for.

This other question provides some of the details.




回答2:


This worked for me

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")


来源:https://stackoverflow.com/questions/39450718/how-to-pass-pil-image-to-add-picture-in-python-pptx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!