From 864826bd6f14b3f522cffc1970725b65f102a0ce Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Thu, 20 Aug 2026 03:12:56 -0400 Subject: [PATCH] Fix ignoring aspect ratio for square images Fix an corner case: Keeping aspect ratio is ignored when inserting a square image into a non-square target rectangle. --- src/__init__.py | 6 +++++- tests/test_insertimage.py | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/__init__.py b/src/__init__.py index c7123b76f..25f7f0bea 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -22669,7 +22669,11 @@ def calc_image_matrix(width, height, tr, rotate, keep): f = fw fw = fh fh = f - if fw < 1: + if keep: + side = min(trw, trh) + w = side + h = side + elif fw < 1: if trw / fw > trh / fh: w = trh * small h = trh diff --git a/tests/test_insertimage.py b/tests/test_insertimage.py index 32d77a282..1c2729864 100644 --- a/tests/test_insertimage.py +++ b/tests/test_insertimage.py @@ -64,3 +64,18 @@ def test_3087(): mask = doc.extract_image(6)["image"] page = doc.new_page() page.insert_image(page.rect, stream=base, mask=mask) + +def test_square_aspect_ratio(): + """Confirm keeping aspect ratio for square images.""" + doc = pymupdf.open() + page = doc.new_page(width=400, height=300) + + # Square red pixmap + pix = pymupdf.Pixmap(pymupdf.csRGB, (0, 0, 100, 100), 0) + pix.set_rect(pix.irect, (255, 0, 0)) + + page.insert_image(page.rect, pixmap=pix) + blocks = page.get_text("blocks", flags=pymupdf.TEXT_PRESERVE_IMAGES) + block = blocks[0] + bbox = pymupdf.Rect(block[:4]) + assert bbox.width == bbox.height