From 38d60ea89b0711d68c9ffaeee0cd486a5e98ae30 Mon Sep 17 00:00:00 2001 From: "James R. Barlow" Date: Wed, 29 Oct 2025 11:39:03 -0700 Subject: [PATCH] optimize: don't put flate on large jpegs unless compression is high Putting flate on very large JPEGs can cause performance problems in PDF viewers, subjectively anyway. --- src/ocrmypdf/optimize.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/ocrmypdf/optimize.py b/src/ocrmypdf/optimize.py index 8d9322f6..a7c6cded 100644 --- a/src/ocrmypdf/optimize.py +++ b/src/ocrmypdf/optimize.py @@ -42,6 +42,7 @@ log = logging.getLogger(__name__) DEFAULT_JPEG_QUALITY = 75 DEFAULT_PNG_QUALITY = 70 +FLATE_JPEG_THRESHOLD = 10000 Xref = NewType('Xref', int) @@ -528,7 +529,19 @@ def _find_deflatable_jpeg( return None _pim, filtdp = result - if filtdp[0] == Name.DCTDecode and not filtdp[1] and options.optimize >= 1: + if ( + filtdp[0] == Name.DCTDecode + and not filtdp[1] + and ( + ( + # Don't flate very large images because it will slow down PDF viewers + 1 <= options.optimize <= 2 + and image.get(Name.Width, 0) < FLATE_JPEG_THRESHOLD + and image.get(Name.Height, 0) < FLATE_JPEG_THRESHOLD + ) + or options.optimize == 3 + ) + ): return XrefExt(xref, '.memory') return None