How to pass PIL image to Add_Picture in python-pptx
Asked Answered
C

3

6

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?

Cyprus answered 12/9, 2016 at 12:49 Comment(0)
G
4

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")
Geotaxis answered 8/10, 2019 at 21:7 Comment(1)
Should be: pic = slide.shapes.add_picture(output, left, top)Stonehenge
L
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.

Linctus answered 12/9, 2016 at 23:3 Comment(0)
O
0

if you have an img as bytes, try this

    print(type(img)) #<class 'bytes'>       
    img_as_file = io.BytesIO()
    img_as_file.write(img)
    slide.shapes.add_picture(img_as_file,left,top)
Opalescent answered 21/10, 2021 at 13:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.