如何使用 docx 从 python 中的列表添加图像?

How do I add an image from a list in python using docx?

我编写了一段代码,该代码截取了我想使用 docx 粘贴到 word 文档中的屏幕截图。到目前为止,我必须将图像保存为 png 文件。我的代码的相关部分是:

from docx import Document
import pyautogui
import docx

doc = Document()

images = []

img = pyautogui.screenshot(region = (some region))

images.append(img)
img.save(imagepath.png)

run =doc.add_picture(imagepath.png)
run

我希望能够在不保存的情况下添加图像。是否可以使用 docx 执行此操作?

是的,根据 add_picture — Document objects — python-docx 0.8.10 documentationadd_picture 也可以从流中导入数据。

根据 Screenshot Functions — PyAutoGUI 1.0.0 documentation, screenshot() produces a PIL/Pillow image object which can be save()'d with a BytesIO() as destination to produce a compressed image data stream in memory.

那就是:

import io
imdata = io.BytesIO()

img.save(imdata, format='png')
imdata.seek(0)

doc.add_picture(imdata)
del imdata    # cannot reuse it for other pictures, you need a clean buffer each time
              # can use .truncate(0) then .seek(0) instead but this is probably easier