Reputation: 79
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?
Upvotes: 6
Views: 3663
Reputation: 489
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)
Upvotes: 0
Reputation: 41
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")
Upvotes: 4
Reputation: 28883
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.
Upvotes: 1