PyMuPDF icon indicating copy to clipboard operation
PyMuPDF copied to clipboard

`Page.get_image_info(xrefs=True)` decodes every image in the page's resources, which makes it O(listed × pages) on documents with a shared /Resources dictionary

Open fsscoc opened this issue 4 weeks ago • 2 comments

Description of the bug

get_image_info(xrefs=True) finds each placed image's xref by decoding every image in page.get_images() and comparing MD5 digests (src/__init__.py, Page.get_image_info):

imglist = page.get_images()
digests = {}
for item in imglist:
    xref = item[0]
    pix = Pixmap(doc, xref)
    digests[pix.digest] = xref

page.get_images() is the page's resources, drawn or not. Many long scanned documents (several hundred pages each, as produced by some document-management exports) put all page images in one /Resources dictionary shared by every page. Each page then lists hundreds or thousands of images and draws one, so every call decodes the whole document's images, and a full pass over the document decodes them once per page.

The docs say the option "has an extended response time, because the MD5 hashcode will be computed at least two times for each image with an xref". In this layout the cost is one decode per listed image per page, which is far more than that.

Impact we measured (PyMuPDF 2.1, Linux x86_64, Python 3.13)

  • A sample of 63 real-world PDFs that our processing could not finish within its time limit: 57 measured so far. In 46 of them, get_image_info(xrefs=True) alone took 10–206 s per page; projected over all pages, that is a median of about 4 hours per document. The pages listed 243 to 4,730 images each and typically drew 1. With the change proposed below, each of these 46 documents takes under 5 minutes for the whole document.
  • On a separate, broader sample of 12,023 pages from 879 PDFs, the xref matching loop accounted for 98.7% of the call's time.
  • One more effect of decoding undrawn images: one bad image that is listed but never drawn, such as an undecodable CCITT image, makes the call raise FzErrorLimit on every page that shares the resources, even though no page draws it.

How to reproduce the bug

The script below builds a 300-page PDF in which all pages share one /Resources dictionary with 300 JPEG scans of the same size, and each page draws one of them. It then times one page:

"""Pages sharing one /Resources dict: each draws 1 image, all N are listed on every page."""
import io, sys, time
import pymupdf
from PIL import Image, ImageDraw

N = int(sys.argv[1]) if len(sys.argv) > 1 else 300
doc = pymupdf.open()
xrefs = []
for i in range(N):
    img = Image.new("RGB", (1240, 1754), "white")  # A4 scan at 150 dpi
    draw = ImageDraw.Draw(img)
    for line in range(20 + (i * 7) % 40):  # a different amount of "text" per scanned page
        draw.text((100, 100 + 40 * line), f"page {i} line {line} " * 6, fill="black")
    buf = io.BytesIO(); img.save(buf, "JPEG", quality=75)
    xref = doc.get_new_xref()
    doc.update_object(xref, f"<</Type/XObject/Subtype/Image/Width 1240/Height 1754"
                            f"/ColorSpace/DeviceRGB/BitsPerComponent 8/Filter/DCTDecode/Length 0>>")
    doc.update_stream(xref, buf.getvalue(), compress=False)
    xrefs.append(xref)
res = doc.get_new_xref()
doc.update_object(res, "<</XObject<<" + "".join(f"/Im{i} {x} 0 R" for i, x in enumerate(xrefs)) + ">>>>")
for i in range(N):
    page = doc.new_page(width=595, height=842)
    doc.xref_set_key(page.xref, "Resources", f"{res} 0 R")
    c = doc.get_new_xref(); doc.update_object(c, "<<>>"); doc.update_stream(c, f"q 595 0 0 842 0 0 cm /Im{i} Do Q".encode())
    doc.xref_set_key(page.xref, "Contents", f"{c} 0 R")
doc.save("shared.pdf", garbage=0)

doc = pymupdf.open("shared.pdf")
page = doc[N // 2]
print("PyMuPDF", pymupdf.VersionBind, "| listed on page:", len(page.get_images()), "| drawn:", len(page.get_image_info()))
t = time.perf_counter(); info = page.get_image_info(xrefs=True); dt = time.perf_counter() - t
print(f"get_image_info(xrefs=True): {dt:.2f}s  xref={info[0]['xref']}")
t = time.perf_counter(); page2 = pymupdf.open("shared.pdf")[N // 2]; info2 = page2.get_image_info(hashes=True); dt = time.perf_counter() - t
print(f"get_image_info(hashes=True): {dt:.2f}s")


def stream_length(doc, xref):
    kind, value = doc.xref_get_key(xref, "Length")
    if kind == "xref":
        value = doc.xref_object(int(value.split()[0]))
    try:
        return int(value)
    except ValueError:
        return None


def image_info_with_xrefs(page):
    """Same result as get_image_info(xrefs=True), decoding only likely candidates."""
    doc = page.parent
    placed = [dict(img) for img in page.get_image_info(hashes=True)]
    listed = page.get_images()
    digests = {}

    def digest_of(xref):
        if xref not in digests:
            digests[xref] = pymupdf.Pixmap(doc, xref).digest
        return digests[xref]

    for img in placed:
        img["xref"] = 0
        # identical pixels imply identical size: only same-size images can match
        same_size = [x[0] for x in listed if (x[2], x[3]) == (img["width"], img["height"])]
        # among those, try first the stream whose /Length is nearest the compressed size
        lengths = {x: stream_length(doc, x) for x in same_size}
        order = sorted(range(len(same_size)), key=lambda i: (
            abs(lengths[same_size[i]] - img["size"]) if lengths[same_size[i]] is not None else float("inf"), -i))
        for i in order:
            if digest_of(same_size[i]) == img["digest"]:
                # keep "last listed wins": check later candidates with the same digest
                img["xref"] = next((x for x in reversed(same_size[i + 1:]) if lengths[x] == lengths[same_size[i]]
                                    and digest_of(x) == img["digest"]), same_size[i])
                break
    return placed


page3 = pymupdf.open("shared.pdf")[N // 2]
t = time.perf_counter(); info3 = image_info_with_xrefs(page3); dt = time.perf_counter() - t
print(f"size + /Length prefilter: {dt:.2f}s  xref={info3[0]['xref']}  same={[i['xref'] for i in info3] == [i['xref'] for i in info]}")

Output:

PyMuPDF 2.1 | listed on page: 300 | drawn: 1
get_image_info(xrefs=True): 4.30s  xref=153
get_image_info(hashes=True): 0.02s
size + /Length prefilter: 0.04s  xref=153  same=True

Without xrefs, the same page takes 0.02 s. Over the 300 pages, xrefs=True takes about 22 minutes, and the cost grows with the square of the page count.

Proposed fix

Decode only the listed images that could be the placed one:

  1. Same pixel size. Identical pixels imply identical width and height, so only listed images whose /Width and /Height equal the placed image's width and height can match. In the general case this alone removes most of the decodes, and it keeps the current result exactly, including "last listed wins" for duplicates.
  2. Nearest /Length first. For scanned documents, where every page image has the same size, try the same-size candidates in order of abs(/Length - placed["size"]). size is the compressed buffer size that extractIMGINFO already reports, and for pass-through filters such as DCT it is within a few bytes of the stream's /Length. The digest still decides the match; the order only changes how many images are decoded. To keep "last wins", check later candidates that have the same /Length and digest.

The script includes a pure-Python version of this, and on the same page it gives the same xref in 0.04 s instead of 4.3 s. On the 12,023-page sample above, the xrefs were identical except on 4 pages. On those 4 pages, an image with identical pixels but a different encoding (a different /Length) appears later in the list. PyMuPDF picks that later copy, and our version picks the earlier one; the pixels are the same. A fix inside PyMuPDF could keep exact semantics by checking every same-size candidate whose digest has not been computed yet only when the /Length match fails.

Two small related points:

  • If /Width or /Height in the dictionary differs from the decoded size (malformed files), step 1 would miss the image. Falling back to the full loop when no same-size candidate matches keeps the result complete.
  • The current loop writes xref into the dicts cached on the page as page._image_info, so a later get_image_info(hashes=True) call returns entries that already carry xref.

We are happy to open a PR if this approach is acceptable.

PyMuPDF version

2.1

Operating system

Linux

Python version

3.13

fsscoc avatar Nov 06 '26 15:11 fsscoc

This is not a bug but an inevitable consequence of your approach. The method internally invokes method get_images() to find matching images in the resources. That method in turn looks for images doing an inheritable search. This is what causes the delay. My advice: do not do this type of thing, or, alternativley, execute page.clean_contents() first.

Gesendet von Outlook für Androidhttps://aka.ms/AAb9ysg


Von: Felipe Silva Santos @.> Gesendet: Freitag, November 6, 2026 11:00:59 AM An: pymupdf/PyMuPDF @.> Cc: Subscribed @.***> Betreff: [pymupdf/PyMuPDF] Page.get_image_info(xrefs=True) decodes every image in the page's resources, which makes it O(listed × pages) on documents with a shared /Resources dictionary (Issue #5260)

[https://avatars.githubusercontent.com/u/17625448?s=20&v=4]fsscoc created an issue (pymupdf/PyMuPDF#5260)https://github.com/pymupdf/PyMuPDF/issues/5260 Description of the bug

get_image_info(xrefs=True) finds each placed image's xref by decoding every image in page.get_images() and comparing MD5 digests (src/init.py, Page.get_image_info):

imglist = page.get_images() digests = {} for item in imglist: xref = item[0] pix = Pixmap(doc, xref) digests[pix.digest] = xref

page.get_images() is the page's resources, drawn or not. Many long scanned documents (several hundred pages each, as produced by some document-management exports) put all page images in one /Resources dictionary shared by every page. Each page then lists hundreds or thousands of images and draws one, so every call decodes the whole document's images, and a full pass over the document decodes them once per page.

The docs say the option "has an extended response time, because the MD5 hashcode will be computed at least two times for each image with an xref". In this layout the cost is one decode per listed image per page, which is far more than that.

Impact we measured (PyMuPDF 2.1, Linux x86_64, Python 3.13)

  • A sample of 63 real-world PDFs that our processing could not finish within its time limit: 57 measured so far. In 46 of them, get_image_info(xrefs=True) alone took 10–206 s per page; projected over all pages, that is a median of about 4 hours per document. The pages listed 243 to 4,730 images each and typically drew 1. With the change proposed below, each of these 46 documents takes under 5 minutes for the whole document.
  • On a separate, broader sample of 12,023 pages from 879 PDFs, the xref matching loop accounted for 98.7% of the call's time.
  • One more effect of decoding undrawn images: one bad image that is listed but never drawn, such as an undecodable CCITT image, makes the call raise FzErrorLimit on every page that shares the resources, even though no page draws it.

How to reproduce the bug

The script below builds a 300-page PDF in which all pages share one /Resources dictionary with 300 JPEG scans of the same size, and each page draws one of them. It then times one page:

"""Pages sharing one /Resources dict: each draws 1 image, all N are listed on every page.""" import io, sys, time import pymupdf from PIL import Image, ImageDraw

N = int(sys.argv[1]) if len(sys.argv) > 1 else 300 doc = pymupdf.open() xrefs = [] for i in range(N): img = Image.new("RGB", (1240, 1754), "white") # A4 scan at 150 dpi draw = ImageDraw.Draw(img) for line in range(20 + (i * 7) % 40): # a different amount of "text" per scanned page draw.text((100, 100 + 40 * line), f"page {i} line {line} " * 6, fill="black") buf = io.BytesIO(); img.save(buf, "JPEG", quality=75) xref = doc.get_new_xref() doc.update_object(xref, f"<</Type/XObject/Subtype/Image/Width 1240/Height 1754" f"/ColorSpace/DeviceRGB/BitsPerComponent 8/Filter/DCTDecode/Length 0>>") doc.update_stream(xref, buf.getvalue(), compress=False) xrefs.append(xref) res = doc.get_new_xref() doc.update_object(res, "<</XObject<<" + "".join(f"/Im{i} {x} 0 R" for i, x in enumerate(xrefs)) + ">>>>") for i in range(N): page = doc.new_page(width=595, height=842) doc.xref_set_key(page.xref, "Resources", f"{res} 0 R") c = doc.get_new_xref(); doc.update_object(c, "<<>>"); doc.update_stream(c, f"q 595 0 0 842 0 0 cm /Im{i} Do Q".encode()) doc.xref_set_key(page.xref, "Contents", f"{c} 0 R") doc.save("shared.pdf", garbage=0)

doc = pymupdf.open("shared.pdf") page = doc[N // 2] print("PyMuPDF", pymupdf.VersionBind, "| listed on page:", len(page.get_images()), "| drawn:", len(page.get_image_info())) t = time.perf_counter(); info = page.get_image_info(xrefs=True); dt = time.perf_counter() - t print(f"get_image_info(xrefs=True): {dt:.2f}s xref={info[0]['xref']}") t = time.perf_counter(); page2 = pymupdf.open("shared.pdf")[N // 2]; info2 = page2.get_image_info(hashes=True); dt = time.perf_counter() - t print(f"get_image_info(hashes=True): {dt:.2f}s")

def stream_length(doc, xref): kind, value = doc.xref_get_key(xref, "Length") if kind == "xref": value = doc.xref_object(int(value.split()[0])) try: return int(value) except ValueError: return None

def image_info_with_xrefs(page): """Same result as get_image_info(xrefs=True), decoding only likely candidates.""" doc = page.parent placed = [dict(img) for img in page.get_image_info(hashes=True)] listed = page.get_images() digests = {}

def digest_of(xref):
    if xref not in digests:
        digests[xref] = pymupdf.Pixmap(doc, xref).digest
    return digests[xref]

for img in placed:
    img["xref"] = 0
    # identical pixels imply identical size: only same-size images can match
    same_size = [x[0] for x in listed if (x[2], x[3]) == (img["width"], img["height"])]
    # among those, try first the stream whose /Length is nearest the compressed size
    lengths = {x: stream_length(doc, x) for x in same_size}
    order = sorted(range(len(same_size)), key=lambda i: (
        abs(lengths[same_size[i]] - img["size"]) if lengths[same_size[i]] is not None else float("inf"), -i))
    for i in order:
        if digest_of(same_size[i]) == img["digest"]:
            # keep "last listed wins": check later candidates with the same digest
            img["xref"] = next((x for x in reversed(same_size[i + 1:]) if lengths[x] == lengths[same_size[i]]
                                and digest_of(x) == img["digest"]), same_size[i])
            break
return placed

page3 = pymupdf.open("shared.pdf")[N // 2] t = time.perf_counter(); info3 = image_info_with_xrefs(page3); dt = time.perf_counter() - t print(f"size + /Length prefilter: {dt:.2f}s xref={info3[0]['xref']} same={[i['xref'] for i in info3] == [i['xref'] for i in info]}")

Output:

PyMuPDF 2.1 | listed on page: 300 | drawn: 1 get_image_info(xrefs=True): 4.30s xref=153 get_image_info(hashes=True): 0.02s size + /Length prefilter: 0.04s xref=153 same=True

Without xrefs, the same page takes 0.02 s. Over the 300 pages, xrefs=True takes about 22 minutes, and the cost grows with the square of the page count.

Proposed fix

Decode only the listed images that could be the placed one:

  1. Same pixel size. Identical pixels imply identical width and height, so only listed images whose /Width and /Height equal the placed image's width and height can match. In the general case this alone removes most of the decodes, and it keeps the current result exactly, including "last listed wins" for duplicates.
  2. Nearest /Length first. For scanned documents, where every page image has the same size, try the same-size candidates in order of abs(/Length - placed["size"]). size is the compressed buffer size that extractIMGINFO already reports, and for pass-through filters such as DCT it is within a few bytes of the stream's /Length. The digest still decides the match; the order only changes how many images are decoded. To keep "last wins", check later candidates that have the same /Length and digest.

The script includes a pure-Python version of this, and on the same page it gives the same xref in 0.04 s instead of 4.3 s. On the 12,023-page sample above, the xrefs were identical except on 4 pages. On those 4 pages, an image with identical pixels but a different encoding (a different /Length) appears later in the list. PyMuPDF picks that later copy, and our version picks the earlier one; the pixels are the same. A fix inside PyMuPDF could keep exact semantics by checking every same-size candidate whose digest has not been computed yet only when the /Length match fails.

Two small related points:

  • If /Width or /Height in the dictionary differs from the decoded size (malformed files), step 1 would miss the image. Falling back to the full loop when no same-size candidate matches keeps the result complete.
  • The current loop writes xref into the dicts cached on the page as page._image_info, so a later get_image_info(hashes=True) call returns entries that already carry xref.

We are happy to open a PR if this approach is acceptable.

PyMuPDF version

2.1

Operating system

Linux

Python version

3.13

— Reply to this email directly, view it on GitHubhttps://github.com/pymupdf/PyMuPDF/issues/5260?email_source=notifications&email_token=AB7IDITZL37IP42MLRJ2UE35XXRSRA5CNFSL4Z3JMQ5C6L3HNF2C22DVMIXUS43TOVSS6NRSGQ2TAMJQGUZDDJTSMVQXG33OVJZXKYTTMNZGSYTFMSSWK5TFNZ2KYZTPN52GK4S7MNWGSY3L, or unsubscribehttps://github.com/notifications/unsubscribe-auth/AB7IDIQH523ESG4J3F2U6CT5XXRSRAVCNFSNUABDKJSXA33TNF2G64TZHM3DCMBVG4YTIO2JONZXKZJ3GYZDINJQGEYDKMRRUF3AE. You are receiving this because you are subscribed to this thread.Message ID: @.***>

JorjMcKie avatar Nov 06 '26 15:11 JorjMcKie

If you want to know the images really shown by the page, page.get_image_info() is the only reliable way. It includes all images: inline images, annotation-based images and of course standard, xref-based images. As you have correctly noticed, the list of xref-based images returned by page.get_images() is

  1. not complete
  2. not guaranteed to actually be visible on the page
  3. PDF-specific (in contrast to get_image_info() - which works for all document types)

While there certainly are ways to streamline the search for xref-based image matches for the list of images returned by .get_image_info(), the most efficient way is to localize the image references, such that .get_images() is guaranteed to only return images in fact referenced by the page. This is done by the extremely fast method page.clean_contents(sanitize=True). Execute this method before using page.get_image_info(..., xref=True)` and you are fine.

JorjMcKie avatar Nov 06 '26 21:11 JorjMcKie