欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python如何在word中存儲(chǔ)本地圖片

 更新時(shí)間:2021年04月07日 16:53:36   作者:烏云飄落  
這篇文章主要介紹了python如何在word中存儲(chǔ)本地圖片,想了解docx模塊的同學(xué),可以參考下

想要利用Python來(lái)操作word文檔可以使用docx模塊.

安裝: 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文檔, 打開之后.

但是有時(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) # 打開圖片
 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)文章!

相關(guān)文章

最新評(píng)論