You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python提取Word文档中带裁剪格式的图片方法求助

解决Word裁剪图片批量提取的Python方案

方案1:直接处理docx文件(推荐,保留原始图片顺序)

用python-docx读取docx内置的裁剪参数,配合Pillow对原始图片做裁剪,完全还原Word内显示效果。

依赖安装

pip install python-docx pillow

可直接运行的代码

from docx import Document
from PIL import Image
import os

# 仅修改这两行路径即可运行
DOCX_PATH = "你的目标文件.docx"  # 替换为你的docx文件路径
SAVE_FOLDER = "裁剪后图片"
os.makedirs(SAVE_FOLDER, exist_ok=True)

doc = Document(DOCX_PATH)
img_index = 0

# 遍历文档内所有关联资源
for rel in doc.part.rels.values():
    if "image" not in rel.target_ref:
        continue
    # 读取原始图片数据
    raw_img = rel.target_part.blob
    temp_path = f"{SAVE_FOLDER}/temp_{img_index}.png"
    with open(temp_path, "wb") as f:
        f.write(raw_img)
    origin_img = Image.open(temp_path)
    w, h = origin_img.size

    # 匹配图片对应的裁剪参数
    for shape in doc.inline_shapes:
        if shape._inline.graphic.graphicData.pic.blipFill.blip.embed != rel.rId:
            continue
        crop_param = shape._inline.graphic.graphicData.pic.blipFill.srcRect
        # 裁剪参数为千分比,转换为实际像素
        left_cut = crop_param.left / 100000 * w
        right_cut = crop_param.right / 100000 * w
        top_cut = crop_param.top / 100000 * h
        bottom_cut = crop_param.bottom / 100000 * h
        # 执行裁剪保存
        cropped_img = origin_img.crop((left_cut, top_cut, w - right_cut, h - bottom_cut))
        cropped_img.save(f"{SAVE_FOLDER}/图片_{img_index}.png")
        img_index += 1
        os.remove(temp_path)
        break

方案2:转PDF后提取(操作更简单,无需处理裁剪参数)

先将Word文件手动另存为PDF,Word转PDF时会自动渲染裁剪后的图片效果,再用PyMuPDF直接提取PDF内的图片即可。

依赖安装

pip install pymupdf

可直接运行的代码

import fitz
import os

# 仅修改这两行路径即可运行
PDF_PATH = "你的转换后文件.pdf"  # 替换为另存的PDF文件路径
SAVE_FOLDER = "裁剪后图片"
os.makedirs(SAVE_FOLDER, exist_ok=True)

pdf_doc = fitz.open(PDF_PATH)
img_index = 0

for page in pdf_doc:
    img_list = page.get_images(full=True)
    for img_info in img_list:
        xref = img_info[0]
        img_data = pdf_doc.extract_image(xref)
        with open(f"{SAVE_FOLDER}/图片_{img_index}.{img_data['ext']}", "wb") as f:
            f.write(img_data["image"])
        img_index += 1

注意事项

  • 两种方案都支持批量处理,90张图片几秒即可完成导出,无需手动操作
  • 初学者直接复制代码,修改对应文件路径即可运行

内容的提问来源于stack exchange,提问作者Renta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:45:01