安裝: pip install python-docx
from docx import Document from docx.shared import Inches string = '文字內(nèi)容' images = '1.jpg' # 保存在本地的圖片 doc = Document() # doc對(duì)象 doc.add_paragraph(string) # 添加文字 doc.add_picture(images, width=Inches(2)) # 添加圖, 設(shè)置寬度 doc.save('word文檔.docx') # 保存路徑
執(zhí)行結(jié)果: 本地生成了一個(gè)Word文檔, 打開(kāi)之后.
但是有時(shí)添加圖片會(huì)產(chǎn)生識(shí)別異常:
這是因?yàn)閳D片的格式問(wèn)題, 對(duì)比一下 0.jpg 和 1.jpg的二進(jìn)制數(shù)據(jù), 添加0.jpg會(huì)異常, 1.jpg則不會(huì).
圖片格式轉(zhuǎn)換
from docx import Document from docx.shared import Inches from PIL import Image string = '文字內(nèi)容' images = '0.jpg' # 保存在本地的圖片 doc = Document() doc.add_paragraph(string) # 添加文字 try: doc.add_picture(images, width=Inches(2)) # 添加圖, 設(shè)置寬度 except Exception: jpg_ima = Image.open(images) # 打開(kāi)圖片 jpg_ima.save('0.jpg') # 保存新的圖片 doc.add_picture(images, width=Inches(2)) # 添加圖, 設(shè)置寬度 doc.save('word文檔.docx') # 保存路徑
結(jié)果就和前面一樣了:
以上就是python如何在word中存儲(chǔ)本地圖片的詳細(xì)內(nèi)容,更多關(guān)于python本地圖片存儲(chǔ)Word的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
標(biāo)簽:衡水 江蘇 湖州 駐馬店 股票 呼和浩特 中山 畢節(jié)
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python如何在word中存儲(chǔ)本地圖片》,本文關(guān)鍵詞 python,如,何在,word,中,存儲(chǔ),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。