python - 压缩word图片大小

主要分为3个步骤,解压docx文件,压缩图片,压缩文件,需要用到zipfile和pillow

1. 解压docx文件

import zipfile
zip_file = zipfile.ZipFile("./test.docx")
zip_file.extractall("./test")
zip_file.close()

解压后可以在解压的目录里面的word/media找到图片

2. 图片大小压缩

import os
from PIL import Image

def compress_image(file_path, target_size=64, step=10, quality=80):
    o_size = os.path.getsize(file_path) / 1024
    while o_size >= target_size:
        im = Image.open(file_path)
        im.save(file_path, quality=quality)  # quality参数为保存图像的质量,值的范围从1(最差)到95(最佳)
        if quality - step <= 0:
            break
        quality -= step
        o_size = os.path.getsize(file_path) / 1024

for file_name in os.listdir('./test/word/media'):
    compress_image(f'./test/word/media/{file_name}')

3. 打包文件

zip_file = zipfile.ZipFile('test1.docx', 'w')
for path, dirs, filenames in os.walk('./test'):
    fpath = path.replace('./test', '')
    for filename in filenames:
        zip_file.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip_file.close()

附上效果图
压缩前图片
image
压缩后图片
image

posted @ 2023-12-19 21:19  wstong  阅读(32)  评论(0编辑  收藏  举报