Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 77e7902

Browse files
committedJun 3, 2025·
Adding Document rewrite images method
1 parent c469893 commit 77e7902

File tree

4 files changed

+176
-1
lines changed

4 files changed

+176
-1
lines changed
 

‎docs/document.rst

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ For details on **embedded files** refer to Appendix 3.
9696
:meth:`Document.pdf_catalog` PDF only: :data:`xref` of catalog (root)
9797
:meth:`Document.pdf_trailer` PDF only: trailer source
9898
:meth:`Document.prev_location` return (chapter, pno) of preceding page
99+
:meth:`Document.rewrite_images` PDF only: rewrite / extra compression for images
99100
:meth:`Document.recolor` PDF only: execute :meth:`Page.recolor` for all pages
100101
:meth:`Document.reload_page` PDF only: provide a new copy of a page
101102
:meth:`Document.resolve_names` PDF only: Convert destination names into a Python dict
@@ -592,9 +593,82 @@ For details on **embedded files** refer to Appendix 3.
592593
To maintain a consistent API, for document types not supporting a chapter structure (like PDFs), :attr:`Document.chapter_count` is 1, and pages can also be loaded via tuples *(0, pno)*. See this [#f3]_ footnote for comments on performance improvements.
593594

594595

596+
.. method:: rewrite_images(dpi_threshold=0, dpi_target=0, quality=0, lossy=True, lossless=True, bitonal=True, color=True, gray=True, set_to_gray=False, options=None)
597+
598+
PDF only: Walk through all images and rewrite them according to the specified parameters. This is useful for reducing file size, changing image formats, or converting color spaces.
599+
600+
The typical usage is extra compression of images for significantly reducing the file size of the PDF. When setting quality and the dpi parameters to positive values and accepting defaults for the rest, the following will happen:
601+
602+
* Lossy and lossless images will be rewritten as JPEG images (as far as technically possible).
603+
604+
* Bitonal (monochrome) images will be rewritten in FAX format (``/Filter /CCITTFaxDecode``).
605+
606+
* Subsampling method is **"average"** (see below).
607+
608+
:arg int dpi_target: target DPI value for the rewritten images. Default is 0, which means that no resampling will take place. If positive, then ``dpi_threshold`` must be larger.
609+
610+
:arg int dpi_threshold: only images with a DPI value larger than this will be rewritten. Default is 0, in which case ``dpi_target`` must also be 0.
611+
612+
:arg int quality: target quality. This is a value between 0 and 100. For lossy images, this is the JPEG quality. For PNG images, this is translated to the compression level (0 = no compression, 100 = maximum compression). Default is 0, which means that no quality changes will take place.
613+
614+
:arg bool lossy: include lossy image types (e.g. JPEG).
615+
616+
:arg bool lossless: include lossless image types (e.g. PNG).
617+
618+
:arg bool bitonal: include black-and-white images (e.g. FAX).
619+
620+
:arg bool color: include colored images.
621+
622+
:arg bool gray: include grayscale images.
623+
624+
:arg bool set_to_gray: if True, the PDF will be converted to grayscale by executing :meth:`Document.recolor` before all image processing. Please note that this will also change text and vector graphics to grayscale -- not just the images.
625+
626+
:arg dict options: This parameter is intended for expert users. Except ``set_to_gray``, all other parameters are ignored. It must be an object prepared in the following way: ``options = pymupdf.mupdf.PdfImageRewriterOptions()``. Then attributes of this object can be set to achieve fine-grained control. Following are the adjustable attributes of the ``options`` object and their default (do nothing) values.
627+
628+
::
629+
630+
options.bitonal_image_recompress_method = 0
631+
options.bitonal_image_recompress_quality = None
632+
options.bitonal_image_subsample_method = 0
633+
options.bitonal_image_subsample_threshold = 0
634+
options.bitonal_image_subsample_to = 0
635+
options.color_lossless_image_recompress_method = 0
636+
options.color_lossless_image_recompress_quality = None
637+
options.color_lossless_image_subsample_method = 0
638+
options.color_lossless_image_subsample_threshold = 0
639+
options.color_lossless_image_subsample_to = 0
640+
options.color_lossy_image_recompress_method = 0
641+
options.color_lossy_image_recompress_quality = None
642+
options.color_lossy_image_subsample_method = 0
643+
options.color_lossy_image_subsample_threshold = 0
644+
options.color_lossy_image_subsample_to = 0
645+
options.gray_lossless_image_recompress_method = 0
646+
options.gray_lossless_image_recompress_quality = None
647+
options.gray_lossless_image_subsample_method = 0
648+
options.gray_lossless_image_subsample_threshold = 0
649+
options.gray_lossless_image_subsample_to = 0
650+
options.gray_lossy_image_recompress_method = 0
651+
options.gray_lossy_image_recompress_quality = None
652+
options.gray_lossy_image_subsample_method = 0
653+
options.gray_lossy_image_subsample_threshold = 0
654+
options.gray_lossy_image_subsample_to = 0
655+
656+
The ``*_recompress_method`` attributes may be one of the values **0 (never), 1 (same), 2 (lossless), 3 (JPEG), 4 (J2K), 5 (FAX)**. Value 0 will skip this image type altogether and 1 will not change the type. The other values will execute type conversions (as far as technically possible).
657+
658+
The ``*_quality`` values are strings of integers from "0" to "100" or ``None``.
659+
660+
The ``*_subsample_method`` attributes are either **0 (average)** or **1 (bicubic interpolation)** and refer to how a pixel value is derived from its neighboring pixels during subsampling. For some background see `here <https://en.wikipedia.org/wiki/Bicubic_interpolation>`_.
661+
662+
Attributes ``*_subsample_threshold`` excludes images from subsampling which have a lower DPI. Participating images will be subsampled to the DPI values given by the ``*_subsample_to`` values. Values of 0 mean that no subsampling will take place.
663+
664+
The ``*_subsample_threshold`` values should be chosen notably larger than the ``*_subsample_to`` values to ensure that there are enough size savings. After all, every subsampling inevitably incurs quality losses.
665+
666+
An example for a good choice is ``threshold=100`` and ``to=72``.
667+
668+
595669
.. method:: recolor(components=1)
596670

597-
PDF only: Change the color component counts for all object types text, image and vector graphics for all pages.
671+
PDF only: Change the color component counts for all object types text, images and vector graphics for all pages.
598672

599673
:arg int components: desired color space indicated by the number of color components: 1 = DeviceGRAY, 3 = DeviceRGB, 4 = DeviceCMYK.
600674

‎src/__init__.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5334,6 +5334,92 @@ def resolve_link(self, uri=None, chapters=0):
53345334
pno = mupdf.fz_page_number_from_location(self.this, loc)
53355335
return pno, xp, yp
53365336

5337+
def rewrite_images(
5338+
self,
5339+
dpi_threshold=0,
5340+
dpi_target=0,
5341+
quality=0,
5342+
lossy=True,
5343+
lossless=True,
5344+
bitonal=True,
5345+
color=True,
5346+
gray=True,
5347+
set_to_gray=False,
5348+
options=None,
5349+
):
5350+
"""Rewrite images in a PDF document.
5351+
5352+
The typical use case is to reduce the size of the PDF by recompressing
5353+
images. Default parameters will convert all images to JPEG where
5354+
possible, using the specified resolutions and quality. Exclude
5355+
undesired images by setting parameters to False.
5356+
Args:
5357+
dpi_threshold: look at images with a larger DPI only.
5358+
dpi_target: change eligible images to this DPI.
5359+
quality: Quality of the recompressed images (0-100).
5360+
lossy: process lossy image types (e.g. JPEG).
5361+
lossless: process lossless image types (e.g. PNG).
5362+
bitonal: process black-and-white images (e.g. FAX)
5363+
color: process colored images.
5364+
gray: prcess gray images.
5365+
set_to_gray: whether to change the PDF to gray at process start.
5366+
options: (PdfImageRewriterOptions) Custom options for image
5367+
rewriting (optional). Expert use only. If provided, other
5368+
parameters are ignored, except set_to_gray.
5369+
"""
5370+
quality_str = str(quality)
5371+
if dpi_target > 0 and not dpi_threshold > dpi_target:
5372+
raise ValueError("dpi_target must be greater than dpi_threshold")
5373+
template_opts = mupdf.PdfImageRewriterOptions()
5374+
dir1 = set(dir(template_opts)) # for checking that only existing options are set
5375+
if not options:
5376+
opts = mupdf.PdfImageRewriterOptions()
5377+
if bitonal:
5378+
opts.bitonal_image_recompress_method = mupdf.FZ_RECOMPRESS_FAX
5379+
opts.bitonal_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
5380+
opts.bitonal_image_subsample_to = dpi_target
5381+
opts.bitonal_image_recompress_quality = quality_str
5382+
opts.bitonal_image_subsample_threshold = dpi_threshold
5383+
if color:
5384+
if lossless:
5385+
opts.color_lossless_image_recompress_method = mupdf.FZ_RECOMPRESS_JPEG
5386+
opts.color_lossless_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
5387+
opts.color_lossless_image_subsample_to = dpi_target
5388+
opts.color_lossless_image_subsample_threshold = dpi_threshold
5389+
opts.color_lossless_image_recompress_quality = quality_str
5390+
if lossy:
5391+
opts.color_lossy_image_recompress_method = mupdf.FZ_RECOMPRESS_JPEG
5392+
opts.color_lossy_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
5393+
opts.color_lossy_image_subsample_threshold = dpi_threshold
5394+
opts.color_lossy_image_subsample_to = dpi_target
5395+
opts.color_lossy_image_recompress_quality = quality_str
5396+
if gray:
5397+
if lossless:
5398+
opts.gray_lossless_image_recompress_method = mupdf.FZ_RECOMPRESS_JPEG
5399+
opts.gray_lossless_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
5400+
opts.gray_lossless_image_subsample_to = dpi_target
5401+
opts.gray_lossless_image_subsample_threshold = dpi_threshold
5402+
opts.gray_lossless_image_recompress_quality = quality_str
5403+
if lossy:
5404+
opts.gray_lossy_image_recompress_method = mupdf.FZ_RECOMPRESS_JPEG
5405+
opts.gray_lossy_image_subsample_method = mupdf.FZ_SUBSAMPLE_AVERAGE
5406+
opts.gray_lossy_image_subsample_threshold = dpi_threshold
5407+
opts.gray_lossy_image_subsample_to = dpi_target
5408+
opts.gray_lossy_image_recompress_quality = quality_str
5409+
else:
5410+
opts = options
5411+
5412+
dir2 = set(dir(opts)) # checking that only possible options were used
5413+
invalid_options = dir2 - dir1
5414+
if invalid_options:
5415+
raise ValueError(f"Invalid options: {invalid_options}")
5416+
5417+
if set_to_gray:
5418+
self.recolor(1)
5419+
pdf = _as_pdf_document(self)
5420+
mupdf.pdf_rewrite_images(pdf, opts)
5421+
5422+
53375423
def recolor(self, components=1):
53385424
"""Change the color component count on all pages.
53395425

645 KB
Binary file not shown.

‎tests/test_rewrite_images.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import pymupdf
2+
import os
3+
4+
scriptdir = os.path.dirname(__file__)
5+
6+
7+
def test_rewrite_images():
8+
"""Example for decreasing file size by more than 30%."""
9+
filename = os.path.join(scriptdir, "resources", "test-rewrite-images.pdf")
10+
doc = pymupdf.open(filename)
11+
size0 = os.path.getsize(doc.name)
12+
doc.rewrite_images(dpi_threshold=100, dpi_target=72, quality=33)
13+
data = doc.tobytes(garbage=3, deflate=True)
14+
size1 = len(data)
15+
assert (1 - (size1 / size0)) > 0.3

0 commit comments

Comments
 (0)
Please sign in to comment.