[英]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.