在python中從word文檔中提取圖像

一張圖片勝過千言萬語。這就是圖像成為文檔不可或缺的一部分的原因,特別是 Word 文檔。圖像用於使內容更具吸引力和引人注目。在解析Word文檔時,可能會遇到需要提取圖片的場景。為了以編程方式實現這一點,本文介紹瞭如何使用 Python 從 Word DOC DOCX 中提取圖像。

從 Word DOC DOCX 文檔中提取圖像的 Python 庫

Aspose.Words for Python 是一個功能強大且功能豐富的庫,用於創建和操作 Word 文檔。我們將使用此庫從 DOCX 或 DOC 文件中提取圖像。您可以使用以下 pip 命令從 PyPI 將其安裝到您的 Python 應用程序中。

pip install aspose-words

在 Python 中從 Word DOC 中提取圖像

Word 文檔中的圖像由形狀節點表示。因此,要從文檔中檢索圖像,您必須解析形狀。以下步驟展示瞭如何使用 Python 從 Word DOC 中提取圖像。

  • 首先,使用 Document 類加載 Word 文檔。
  • 然後,使用 Document.getchildnodes(NodeType.SHAPE, True) 方法將所有形狀檢索到一個對像中。
  • 遍歷形狀並為每個形狀執行以下操作:
    • 使用 asshape() 方法將形狀轉換為 Shape 類型。
    • 使用 Shape.hasimage() 方法檢查形狀是否有圖像。
    • 使用 Shape.imagedata.save(string) 方法將形狀保存為圖像。

以下代碼示例展示瞭如何使用 Python 從 Word DOCX 文檔中提取圖像。

import aspose.words as aw

# 載入Word文檔
doc = aw.Document("calibre.docx")

# 檢索所有形狀
shapes = doc.get_child_nodes(aw.NodeType.SHAPE, True)
imageIndex = 0

# 遍歷形狀
for shape in shapes :
    shape = shape.as_shape()
    if (shape.has_image) :

        # 設置圖片文件名
        imageFileName = f"Image.ExportImages.{imageIndex}_{aw.FileFormatUtil.image_type_to_extension(shape.image_data.image_type)}"

        # 保存圖片
        shape.image_data.save(imageFileName)
        imageIndex += 1

從 DOC DOCX 中提取圖像的 API - 獲取免費的 API 許可證

您可以獲得 臨時許可 以在沒有評估限制的情況下使用 Aspose.Words for Python。

結論

圖像通常用於 Word 文檔中,以使內容更具吸引力。在各種情況下,還需要將圖像與文本一起從文檔中提取出來。因此,在本文中,您學習瞭如何使用 Python 從 Word DOC DOCX 文檔中提取圖像。除此之外,您還可以探索 Aspose.Words for Python 的文檔。如果您有任何疑問,請隨時通過我們的 論壇 告訴我們。

也可以看看

信息:如果您需要從 PowerPoint 演示文稿中獲取 Word 文檔,您可以使用 Aspose Presentation to Word Document 轉換器。