python add picture显示过大_如何在python-pptx中将PIL图像传递到Add_Picture

在尝试使用Python的python-pptx库将从剪贴板抓取的图片直接添加到PPTX演示文稿时,遇到了AttributeError: read。错误原因是PIL库中的Image对象不支持直接读取。解决方案是将图片保存到内存中的BytesIO对象,然后通过这个对象添加到幻灯片中。
摘要由CSDN通过智能技术生成

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?

解决方案

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值