Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pil() method #3911

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/installation.rst
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ Notes

* There are no **mandatory** external dependencies. However, some optional feature are available only if additional components are installed:

* `Pillow <https://pypi.org/project/Pillow/>`_ is required for :meth:`Pixmap.pil_save` and :meth:`Pixmap.pil_tobytes`.
* `Pillow <https://pypi.org/project/Pillow/>`_ is required for :meth:`Pixmap.pil`, :meth:`Pixmap.pil_save` and :meth:`Pixmap.pil_tobytes`.
* `fontTools <https://pypi.org/project/fonttools/>`_ is required for :meth:`Document.subset_fonts`.
* `pymupdf-fonts <https://pypi.org/project/pymupdf-fonts/>`_ is a collection of nice fonts to be used for text output methods.
* `Tesseract-OCR <https://github.com/tesseract-ocr/tesseract>`_ for optical character recognition in images and document pages. Tesseract is separate software, not a Python package. To enable OCR functions in PyMuPDF, the software must be installed and the system environment variable `"TESSDATA_PREFIX"` must be defined and contain the `tessdata` folder name of the Tesseract installation location. See below.
Expand Down
15 changes: 11 additions & 4 deletions docs/pixmap.rst
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Have a look at the :ref:`FAQ` section to see some pixmap usage "at work".
:meth:`Pixmap.invert_irect` invert the pixels of a given area
:meth:`Pixmap.pdfocr_save` save the pixmap as an OCRed 1-page PDF
:meth:`Pixmap.pdfocr_tobytes` save the pixmap as an OCRed 1-page PDF
:meth:`Pixmap.pil` get as pillow image
:meth:`Pixmap.pil_save` save as image using pillow
:meth:`Pixmap.pil_tobytes` write to `bytes` object using pillow
:meth:`Pixmap.pixel` return the value of a pixel
Expand Down Expand Up @@ -388,7 +389,15 @@ Have a look at the :ref:`FAQ` section to see some pixmap usage "at work".
doc.save("ocr-images.pdf")


.. method:: pil_save(*args, unmultiply=False, **kwargs)
.. method:: pil()

* New in v1.17.3

Get the pixmap as Pillow image object. The returned image has the same colorspace as the pixmap.

:raises ImportError: if Pillow is not installed.

.. method:: pil_save(*args, **kwargs)

* New in v1.17.3

Expand All @@ -400,16 +409,14 @@ Have a look at the :ref:`FAQ` section to see some pixmap usage "at work".

A simple example: `pix.pil_save("some.webp", optimize=True, dpi=(150, 150))`.

:arg bool unmultiply: If the pixmap's colorspace is RGB with transparency, the alpha values may or may not already be multiplied into the color components ref/green/blue (called "premultiplied"). To enforce undoing premultiplication, set this parameter to `True`. To learn about some background, e.g. look for "Premultiplied alpha" `here <https://en.wikipedia.org/wiki/Glossary_of_computer_graphics#P>`_.


For details on other parameters see the Pillow documentation.

Since v1.22.0, PyMuPDF supports JPEG output directly. We recommended to no longer use this method for JPEG output -- for performance reasons and for avoiding unnecessary external dependencies.

:raises ImportError: if Pillow is not installed.

.. method:: pil_tobytes(*args, unmultiply=False, **kwargs)
.. method:: pil_tobytes(*args, **kwargs)

* New in v1.17.3

Expand Down
18 changes: 11 additions & 7 deletions src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10168,12 +10168,8 @@ def pdfocr_tobytes(self, compress=True, language="eng", tessdata=None):
self.pdfocr_save(bio, compress=compress, language=language, tessdata=tessdata)
return bio.getvalue()

def pil_save(self, *args, **kwargs):
"""Write to image file using Pillow.

Args are passed to Pillow's Image.save method, see their documentation.
Use instead of save when other output formats are desired.
"""
def pil(self):
"""Get pixmap as a Pillow image."""
try:
from PIL import Image
except ImportError:
Expand All @@ -10190,7 +10186,15 @@ def pil_save(self, *args, **kwargs):
else:
mode = "CMYK"

img = Image.frombytes(mode, (self.width, self.height), self.samples)
return Image.frombytes(mode, (self.width, self.height), self.samples)

def pil_save(self, *args, **kwargs):
"""Write to image file using Pillow.

Args are passed to Pillow's Image.save method, see their documentation.
Use instead of save when other output formats are desired.
"""
img = self.pil()

if "dpi" not in kwargs.keys():
kwargs["dpi"] = (self.xres, self.yres)
Expand Down
27 changes: 25 additions & 2 deletions tests/test_pixmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import os
import platform
import sys
import tempfile
import pytest
import textwrap

Expand Down Expand Up @@ -57,7 +56,31 @@ def test_filepixmap():
assert pix1.digest == pix2.digest


def test_pilsave():
def test_pil(tmpdir):
# pixmaps from file then get pillow image
# make pixmap from this and confirm equality
try:
pix1 = pymupdf.Pixmap(imgfile)
pix1.pil().save(tmpdir / "foo.png")
pix2 = pymupdf.Pixmap(str(tmpdir / "foo.png"))
assert repr(pix1) == repr(pix2)
except ModuleNotFoundError:
assert platform.system() == 'Windows' and sys.maxsize == 2**31 - 1


def test_pil_save(tmpdir):
# pixmaps from file then save pillow image to temporary file
# make pixmap from this and confirm equality
try:
pix1 = pymupdf.Pixmap(imgfile)
pix1.pil_save(tmpdir / "foo.png")
pix2 = pymupdf.Pixmap(str(tmpdir / "foo.png"))
assert repr(pix1) == repr(pix2)
except ModuleNotFoundError:
assert platform.system() == 'Windows' and sys.maxsize == 2**31 - 1


def test_pil_tobytes():
# pixmaps from file then save to pillow image
# make pixmap from this and confirm equality
try:
Expand Down
Loading