>>> from env_helper import info; info()
页面更新时间: 2024-04-06 23:06:08
运行环境:
    Linux发行版本: Debian GNU/Linux 12 (bookworm)
    操作系统内核: Linux-6.1.0-18-amd64-x86_64-with-glibc2.36
    Python版本: 3.11.2

3.12. 实例:对 DOCX 中的图片进行批量处理

3.12.1. 场景描述

想要同时修改word文档内的多个图片。

3.12.2. 解决思路

这里不使用 Python 的 docx 模块。 前已述及, DOCX 实质上就是一个压缩文件,图片都是以资源的方式存储在其中。 要对其中的图片进行处理,可以解压缩文件,处理之后,再压缩成为 DOCX 格式。

3.12.3. 解决方法

>>> import shutil
>>> import zipfile
>>> import os
>>> zipf = zipfile.ZipFile('./docx/case_imgs.docx')
>>>
>>> tmp_dir = '/tmp/wd'
>>>
>>> if os.path.exists(tmp_dir):
>>>     shutil.rmtree(tmp_dir)
>>> else:
>>>     os.mkdir(tmp_dir)
>>> zipf.extractall(tmp_dir)

然后是对图片的处理,这里只是转换成灰度图。需要注意的是 docx 格式的文件解压缩后有固定结构。 对于图像文件,是放到解压目录下的 word/media 文件夹中。

>>> from PIL import Image
>>> inws = f'{tmp_dir}/word/media'
>>> for x in os.listdir(inws):
>>>     if x.endswith('jpeg'):
>>>         print(x)
>>>         infile = os.path.join(inws, x)
>>>         im = Image.open(infile).convert("L")
>>>         im.save(infile)
image2.jpeg
image3.jpeg
image6.jpeg
image5.jpeg
image1.jpeg
image4.jpeg

最后进行压缩:

>>> from shutil import make_archive
>>> import os
>>>
>>> archive_name =os.path.join('.', 'xx_out')
>>> root_dir = os.path.join(tmp_dir)
>>> make_archive(archive_name, 'zip', root_dir, base_dir = '.')
'/home/bk/book-jubook/python/jubook_python/pt05_tool/ch03_imgs/xx_out.zip'

将压缩的结果重命名为 docx 后缀的文件:

>>> shutil.move(archive_name + '.zip', archive_name + '.docx')
'./xx_out.docx'