办公问答网

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 91|回复: 2

Python提取Word中的所有图片

[复制链接]

1

主题

5

帖子

7

积分

新手上路

Rank: 1

积分
7
发表于 2022-12-22 20:28:56 | 显示全部楼层 |阅读模式
原理说明

.docx文件其实也就是一个压缩文件,当我们将一个.docx文件直接解压后可以看到_rels、docProps、word三个文件夹和文件[Content_Types].xml,其中我们要找的图片就在word/media目录内。因此,要提取word内的图片可以考虑将.docx文件解压,再从word/media文件内提取图片,最后将解压后的临时文件删除即可。
代码实现

完整代码


  • GitHub链接:https://github.com/XiaokangLei/image_toolkit
方法1

import zipfile
import os
import shutil

def word2img(word_path, result_path):
    tmp_path = f'{os.path.splitext(word_path)[0]}'
    splitext = os.path.splitext(word_path)
    zip_path = shutil.copy(word_path, f'{splitext[0]}_new{splitext[1]}')
    with zipfile.ZipFile(zip_path, 'r') as f:
        for file in f.namelist():
            f.extract(file, tmp_path)
    os.remove(zip_path)
    pic_path = os.path.join(tmp_path, 'word/media')
    if not os.path.exists(pic_path):
        shutil.rmtree(tmp_path)
        return 'no pictures found'
    pictures = os.listdir(pic_path)
    if not os.path.exists(result_path):
        os.makedirs(result_path)
    for picture in pictures:
        word_name = os.path.splitext(word_path)[0]
        if os.sep in word_name:
            new_name = word_name.split('\\')[-1]
        else:
            new_name = word_name.split('/')[-1]
        picture_name = f'{new_name}_{picture}'
        shutil.copy(os.path.join(pic_path, picture), os.path.join(result_path, picture_name))

    shutil.rmtree(tmp_path)
    return (os.path.join(result_path, pic) for pic in os.listdir(result_path))方法2


  • 需要安装docx库:pip install docx
import os
import docx
import re

def word2img2(word_path, result_path):
    doc = docx.Document(word_path)
    dict_rel = doc.part._rels
    for rel in dict_rel:
        rel = dict_rel[rel]
        if "image" in rel.target_ref:
            if not os.path.exists(result_path):
                os.makedirs(result_path)
            img_name = re.findall("/(.*)", rel.target_ref)[0]
            word_name = os.path.splitext(word_path)[0]
            if os.sep in word_name:
                new_name = word_name.split('\\')[-1]
            else:
                new_name = word_name.split('/')[-1]
            img_name = f'{new_name}_{img_name}'
            with open(f'{result_path}/{img_name}', "wb") as f:
                f.write(rel.target_part.blob)
回复

使用道具 举报

0

主题

8

帖子

12

积分

新手上路

Rank: 1

积分
12
发表于 2025-5-31 11:42:28 | 显示全部楼层
前排,哇咔咔
回复

使用道具 举报

2

主题

11

帖子

20

积分

新手上路

Rank: 1

积分
20
发表于 2025-6-1 17:59:52 | 显示全部楼层
看起来好像不错的样子
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|办公问答网

GMT+8, 2025-7-5 05:34 , Processed in 0.085119 second(s), 23 queries .

Powered by Discuz! X3.4

© 2001-2013 Comsenz Inc. Templated By 【未来科技 www.veikei.com】设计

快速回复 返回顶部 返回列表