
本文详解如何解决 page.get_text("dict") 返回的图像块中 xref 不可用的问题,通过结合 page.get_images() 与 page.get_image_rects() 精确匹配图像位置与实际 xref,实现可靠图像提取与文本占位符插入。
本文详解如何解决 `page.get_text("dict")` 返回的图像块中 `xref` 不可用的问题,通过结合 `page.get_images()` 与 `page.get_image_rects()` 精确匹配图像位置与实际 xref,实现可靠图像提取与文本占位符插入。
在使用 PyMuPDF(fitz)解析 PDF 时,一个常见误区是直接从 page.get_text("dict")["blocks"] 中获取图像块(block['type'] == 1)的 block['image'][0] 作为 xref 调用 doc.extract_image(xref)——该值并非真正的对象交叉引用号(xref),而是内部缓存索引或无效标识,直接使用必然触发 ValueError: bad xref。
根本原因在于:get_text("dict") 的图像块仅提供粗略的渲染信息(如 bbox、width、height),其 image 字段不保证包含有效 xref;而真正可提取的图像资源需通过 page.get_images() 获取完整图像描述元组,并借助 page.get_image_rects() 定位其在页面上的精确坐标,再进行空间匹配。
✅ 正确做法是:
- 遍历 page.get_text("dict")["blocks"],识别图像块并记录其边界框(bbox)与尺寸;
- 调用 page.get_images() 获取当前页所有嵌入图像的 (xref, smask, width, height, bpc, ...) 元组列表;
- 对每个候选图像,用 page.get_image_rects(xref) 获取其在页面上所有出现位置(支持图像复用);
- 将图像块的 bbox 与各 image_rect 坐标做浮点容差比对(建议四舍五入至小数点后 3 位),匹配成功即获得真实 xref。
以下是修正后的完整函数(含依赖说明与关键注释):
import fitz
import numpy as np
def extract_text_and_save_images(pdf_path):
doc = fitz.open(pdf_path)
full_text = ""
image_counter = 1
for page_num in range(len(doc)):
page = doc.load_page(page_num)
blocks = page.get_text("dict")["blocks"]
# 获取当前页所有图像资源(含真实 xref)
page_images = page.get_images(full=True) # full=True 返回详细元组
for block in blocks:
if block['type'] == 0: # 文本块
for line in block.get("lines", []):
for span in line.get("spans", []):
full_text += span["text"] + " "
full_text += "\n"
elif block['type'] == 1: # 图像块
# 提取图像块位置与尺寸(用于后续匹配)
block_bbox = np.round(block["bbox"], decimals=3)
block_width = round(block["width"])
block_height = round(block["height"])
# 在 page_images 中查找尺寸匹配的图像候选
candidates = [
img for img in page_images
if round(img[2]) == block_width and round(img[3]) == block_height
]
xref = None
for img in candidates:
# 获取该 xref 在当前页的所有绘制位置(支持重复使用同一图像)
rects = page.get_image_rects(img[0])
for rect in rects:
rect_pos = np.round(rect, decimals=3)
# 坐标完全匹配则确认为对应图像
if (np.allclose(rect_pos[:2], block_bbox[:2], atol=0.1) and
np.allclose(rect_pos[2:], block_bbox[2:], atol=0.1)):
xref = img[0]
break
if xref is not None:
break
if xref is None:
print(f"⚠️ Warning: No matching xref found for image block on page {page_num}")
full_text += f">>\n"
image_counter += 1
continue
# ✅ 使用真实 xref 提取图像
try:
base_image = doc.extract_image(xref)
image_bytes = base_image["image"]
image_filename = f"image_{image_counter}.png"
with open(image_filename, "wb") as f:
f.write(image_bytes)
full_text += f">>\n"
image_counter += 1
except Exception as e:
print(f"❌ Failed to extract image {image_counter} (xref={xref}): {e}")
full_text += f">>\n"
image_counter += 1
doc.close()
return full_text
? 关键注意事项:
- page.get_images(full=True) 是必需的——full=False(默认)仅返回 (xref, smask) 二元组,丢失尺寸信息,无法过滤;
- page.get_image_rects(xref) 返回的是 fitz.Rect 对象列表,每个代表该图像在页面上的一个绘制实例(PDF 支持单图多次复用);
- 坐标匹配务必使用 np.round(..., 3) 或 np.allclose(..., atol=0.1),避免浮点精度误差导致匹配失败;
- 某些 PDF 可能包含无内容图像(如透明占位符)、SMask 掩膜或内联图像,extract_image() 可能抛出异常,建议用 try/except 包裹;
- 若需保留图像原始格式(如 JPEG),可检查 base_image["ext"] 并动态设置文件扩展名。
此方案绕过了 get_text("dict") 图像块的 xref 陷阱,以“位置+尺寸”双重校验确保提取可靠性,适用于绝大多数标准 PDF 文档,是 PyMuPDF 图像处理的最佳实践路径。











