使用python-pptx区分PPT中矢量图与位图并为位图添加红框的问题
解决方案
问题根因
矢量图被误判为PNG的核心原因是:Office插入SVG、AI等外部矢量格式时,会自动生成一张PNG格式的预览位图和矢量源数据共同存储在PPTX文件包中,python-pptx默认读取到的是预览图的content_type,因此会出现误判。
修复方案
分两步实现精准过滤:
- 先直接过滤所有明确的矢量格式图片
- 对剩余的图片,检查元素中是否附带矢量数据节点,过滤掉矢量图的预览占位图
修复后的代码
from pptx import Presentation from pptx.dml.color import RGBColor from pptx.util import Pt prs = Presentation("test.pptx") # 定义矢量格式白名单,直接过滤 VECTOR_CONTENT_TYPES = {"image/x-wmf", "image/x-emf", "image/svg+xml", "image/x-emz", "image/x-wmz"} for slide_id, slide in enumerate(prs.slides): for shape in slide.shapes: # 非图片类型直接跳过 if shape.shape_type != 13: continue content_type = shape.image.content_type # 过滤明确的矢量格式 if content_type in VECTOR_CONTENT_TYPES: continue # 检查是否存在矢量数据扩展节点,过滤矢量图的PNG预览 has_vector_data = len(shape._element.xpath(".//*[local-name()='svgBlip' or local-name()='vectorData']")) > 0 if has_vector_data: continue # 剩余为真实位图,添加红框 if content_type in ("image/png", "image/jpeg", "image/jpg"): line = shape.line line.color.rgb = RGBColor(255, 0, 0) line.width = Pt(3.0) prs.save("out.pptx")
补充说明
如果仍存在个别漏判的情况,可额外补充以下判断逻辑:
- 增加图片分辨率校验:大部分矢量预览图的分辨率是固定的,可通过
shape.image.size过滤符合预览尺寸的图片 - 读取图片字节流的头信息,二次校验文件格式真实性
内容的提问来源于stack exchange,提问作者malfroid
相关产品推荐
相关产品推荐

