把word導出成圖片的流程「word中的圖片如何保存為jpg格式」

由於工作中需要從大量docx文檔中提出圖片,於是到網上搜索,找了一大堆都是分析xml文件並提取的,太過於複雜,實際上有更簡單的方法,我們需要用到python-docx這個第三方庫,但該庫並未開發提取圖片功能,不過可以通過其他方法出得到圖片數據並保存為圖片。

本文為原創,如需轉載請註明出處(僅處理docx文檔,不能處理doc文檔,如果需要可執行文件的,可將代碼文件通過pyinstaller進行編譯)。想從word文檔中快速提取圖片嗎?看看在python中如何辦到

軟件界面

下面這段代碼是核心:

    for file in os.listdir(filePath):
        try:
            #跳過非docx文件
            if ".docx" not in file:
                continue
            # 創建imgPath
            subImgPath = imgPath + re.sub(".docx","",file)
            if not os.path.exists(subImgPath):
                os.makedirs(subImgPath)

            doc = docx.Document(filePath + file)        #打開文件
            for rel in doc.part._rels:
                rel = doc.part._rels[rel]               #獲得資源
                if "image" not in rel.target_ref:
                    continue
                imgName = re.findall("/(.*)",rel.target_ref)[0]
                with open(subImgPath + "/" + imgName,"wb") as f:
                    f.write(rel.target_part.blob)
            UI.currentFile.setText("當前文件:" + imgName)
        except:
            continue

後來經過改進,使用PyQt5製作了界面,下面為源代碼:

import docx,re,os,sys,ui_imgExtract
from PyQt5.QtWidgets import QApplication,QMainWindow,QWidget,QMessageBox
from PyQt5.Qt import QFileDialog

def run():
    filePath = UI.filePath.text()
    imgPath = UI.imgPath.text()
    if not os.path.exists(filePath):
        QMessageBox.about(main, "錯誤", "請選擇docx文件目錄!")
        return
    if not os.path.exists(imgPath):
        os.makedirs(imgPath)

    for file in os.listdir(filePath):
        try:
            #跳過非docx文件
            if ".docx" not in file:
                continue
            # 創建imgPath
            subImgPath = imgPath + re.sub(".docx","",file)
            if not os.path.exists(subImgPath):
                os.makedirs(subImgPath)

            doc = docx.Document(filePath + file)        #打開文件
            for rel in doc.part._rels:
                rel = doc.part._rels[rel]               #獲得資源
                if "image" not in rel.target_ref:
                    continue
                imgName = re.findall("/(.*)",rel.target_ref)[0]
                with open(subImgPath + "/" + imgName,"wb") as f:
                    f.write(rel.target_part.blob)
            UI.currentFile.setText("當前文件:" + imgName)
        except:
            continue
    QMessageBox.about(main, "完成", "圖片提取已完成!")

def init():
    UI.btnRun.clicked.connect(run)      #綁定開始提取按鈕
    UI.btnFilePath.clicked.connect(choiceFileDir)  # 綁定選擇docx文件目錄
    UI.btnImgPath.clicked.connect(choiceImgOutPutDir)    #綁定選擇圖片保存目錄

    # docx文件默認目錄
    UI.filePath.setText(os.getcwd())
    #默認輸出目錄
    if not os.path.exists(os.getcwd() + "img\"):
        os.makedirs(os.getcwd() + "img\")
    UI.imgPath.setText(os.getcwd() + "img\")


#選擇docx文件目錄
def choiceFileDir():
    dir = QFileDialog.getExistingDirectory(main, "選擇docx文件目錄", os.getcwd())
    UI.filePath.setText(dir + "/")

#選擇圖片保存目錄
def choiceImgOutPutDir():
    dir = QFileDialog.getExistingDirectory(main, "選擇輸出目錄", os.getcwd())
    UI.imgPath.setText(dir + "/")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = QWidget()
    UI = ui_imgExtract.Ui_Form()
    UI.setupUi(main)
    main.show()
    init()

    sys.exit(app.exec_())

下面是界面文件ui_imgExtract.py:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'ui_iask.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(604, 100)
        self.layoutWidget = QtWidgets.QWidget(Form)
        self.layoutWidget.setGeometry(QtCore.QRect(10, 10, 581, 83))
        self.layoutWidget.setObjectName("layoutWidget")
        self.gridLayout_4 = QtWidgets.QGridLayout(self.layoutWidget)
        self.gridLayout_4.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_4.setObjectName("gridLayout_4")
        self.label_8 = QtWidgets.QLabel(self.layoutWidget)
        self.label_8.setObjectName("label_8")
        self.gridLayout_4.addWidget(self.label_8, 0, 0, 1, 1)
        self.filePath = QtWidgets.QLineEdit(self.layoutWidget)
        self.filePath.setObjectName("filePath")
        self.gridLayout_4.addWidget(self.filePath, 0, 1, 1, 1)
        self.btnFilePath = QtWidgets.QPushButton(self.layoutWidget)
        self.btnFilePath.setObjectName("btnFilePath")
        self.gridLayout_4.addWidget(self.btnFilePath, 0, 2, 1, 1)
        self.label_9 = QtWidgets.QLabel(self.layoutWidget)
        self.label_9.setObjectName("label_9")
        self.gridLayout_4.addWidget(self.label_9, 1, 0, 1, 1)
        self.imgPath = QtWidgets.QLineEdit(self.layoutWidget)
        self.imgPath.setObjectName("imgPath")
        self.gridLayout_4.addWidget(self.imgPath, 1, 1, 1, 1)
        self.btnImgPath = QtWidgets.QPushButton(self.layoutWidget)
        self.btnImgPath.setObjectName("btnImgPath")
        self.gridLayout_4.addWidget(self.btnImgPath, 1, 2, 1, 1)
        self.btnRun = QtWidgets.QPushButton(self.layoutWidget)
        self.btnRun.setObjectName("btnRun")
        self.gridLayout_4.addWidget(self.btnRun, 2, 2, 1, 1)
        self.currentFile = QtWidgets.QLabel(self.layoutWidget)
        self.currentFile.setObjectName("currentFile")
        self.gridLayout_4.addWidget(self.currentFile, 2, 0, 1, 2)

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "docx圖片批量提取"))
        self.label_8.setText(_translate("Form", "docx文件目錄:"))
        self.btnFilePath.setText(_translate("Form", "選擇"))
        self.label_9.setText(_translate("Form", "圖片保存目錄:"))
        self.btnImgPath.setText(_translate("Form", "選擇"))
        self.btnRun.setText(_translate("Form", "開始提取"))
        self.currentFile.setText(_translate("Form", "當前文件:"))

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/269005.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-16 13:13
下一篇 2024-12-16 13:13

相關推薦

發表回復

登錄後才能評論