【问题标题】:Extract all the images in a docx file using python使用python提取docx文件中的所有图像
【发布时间】:2020-05-28 18:47:25
【问题描述】:

我有一个包含 6-7 张图片的 docx 文件。我需要自动从此 doc 文件中提取图像。是否有相同的win32com ms word API?或者有什么库可以准确提取其中的所有图片?

这是我尝试过的,但问题首先是它没有给我所有的图像,其次它给了我很多错误的积极图像,比如空白图像、极小的图像、线条等...... 它也使用 MS 词来做同样的事情。

from pathlib import Path
from win32com.client import Dispatch

xls = Dispatch("Excel.Application")
doc = Dispatch("Word.Application")


def export_images(fp, prefix="img_", suffix="png"):
    """ export all of images(inlineShapes) in the word file.
    :param fp: path of word file.
    :param prefix: prefix of exported images.
    :param suffix: suffix of exported images.
    """

    fp = Path(fp)
    word = doc.Documents.Open(str(fp.resolve()))
    sh = xls.Workbooks.Add()
    for idx, s in enumerate(word.inlineShapes, 1):
        s.Range.CopyAsPicture()
        d = sh.ActiveSheet.ChartObjects().add(0, 0, s.width, s.height)
        d.Chart.Paste()
        d.Chart.Export(fp.parent / ("%s_%s.%s" % (prefix, idx, suffix))
    sh.Close(False)
    word.Close(False)
export_images(r"C:\Users\HPO2KOR\Desktop\Work\venv\us2017010202.docx")

你可以在这里https://drive.google.com/open?id=1xdw2MieI1n3ulXlkr_iJSKb3cbozdvWq下载docx文件

【问题讨论】:

    标签: python image docx glob win32com


    【解决方案1】:

    在您的枚举循环中,您可能应该检查形状类型是否为图片:

    for idx, s in enumerate(word.inlineShapes, 1):
        if s.Type != 3: # wdInlineShapePicture
            continue
        # ...
    

    【讨论】:

    • 我还是没有得到所有 6-7 张图片
    • 作为通用提示,您可以使用 Word 宏编辑器 (Alt+F11) 更准确地说是“直接窗口” (Ctrl+G) 来使用对象模型并检查实际数据结构。
    • 嗨@Torben新手,如果你能解释一下,那将是非常好的
    • 很难在评论中做到。也很容易找到很多材料:google.com/search?q=vba+editor+tutorial
    【解决方案2】:

    你可以解压来自docx的所有图片,初步按大小过滤:

    import zipfile
    
    archive = zipfile.ZipFile('file.docx')
    for file in archive.filelist:
        if file.filename.startswith('word/media/') and file.file_size > 300000:
            archive.extract(file)
    

    your example5 找到图片:

    【讨论】:

    • 如何删除那些多余的图片
    • 您可以按大小过滤它们。请参阅我的更新答案。
    • 由于某种原因,某些图像的显示方向错误。例如,在 word 中,我将从一个空白文档开始。我插入了一些 JPEGS,其源文件是纵向的。它们在 Word 文档中保持纵向。我保存文档,然后在 Word 文件上运行上述代码。提取的图像现在是横向的(从原始源文件和 Word 文档逆时针旋转 90 度)。
    【解决方案3】:

    添加另一种方法来做同样的事情。我们可以使用doc2txt库来获取所有的图片

    import docx2txt
    text = docx2txt.process("docx_file", r"directory where you want to store the images")
    

    请注意,它还会在 text 变量中提供文件中找到的所有文本。

    【讨论】:

      【解决方案4】:

      使用python提取docx文件中的所有图片

      1。使用 docxtxt

      import docx2txt
      #extract text 
      text = docx2txt.process(r"filepath_of_docx")
      #extract text and write images in Temporary Image directory
      text = docx2txt.process(r"filepath_of_docx",r"Temporary_Image_Directory")
      

      2。使用 aspose

      import aspose.words as aw
      # load the Word document
      doc = aw.Document(r"filepath")
      # retrieve all shapes
      shapes = doc.get_child_nodes(aw.NodeType.SHAPE, True)
      imageIndex = 0
      # loop through shapes
      for shape in shapes :
          shape = shape.as_shape()
          if (shape.has_image) :
              # set image file's name
              imageFileName = f"Image.ExportImages.{imageIndex}_{aw.FileFormatUtil.image_type_to_extension(shape.image_data.image_type)}"
              # save image
              shape.image_data.save(imageFileName)
              imageIndex += 1
      

      【讨论】:

      • 不要在多个问题上发布identical answers。请根据具体问题自定义这些答案。
      猜你喜欢
      • 1970-01-01
      • 2014-10-03
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 2020-04-10
      相关资源
      最近更新 更多