我编写了一个代码,其中包含要使用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来做到这一点吗?
答案 0 :(得分:1)
是的,根据add_picture — Document objects — python-docx 0.8.10 documentation,add_picture
也可以从流中导入数据。
根据Screenshot Functions — PyAutoGUI 1.0.0 documentation,screenshot()
产生一个can be save()
'd with a BytesIO()
as destination to produce a compressed image data stream in memory的PIL /枕头图像对象。
因此它将是:
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