[英]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 — 文档对象 — python-docx 0.8.10 文档, add_picture
也可以从 stream 导入数据。
As per 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.