### Build and Install Pillow from Source Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Standard commands to install Pillow from source, including an example for specifying non-standard library locations via environment variables. ```bash python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow --no-binary :all: ``` ```bash CFLAGS="-I/usr/pkg/include" python3 -m pip install --upgrade Pillow --no-binary :all: ``` -------------------------------- ### Enable features during installation Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Example command to force the enablement of a specific feature during the build process. ```bash python3 -m pip install --upgrade Pillow -C [feature]=enable ``` -------------------------------- ### Install optional dependencies Source: https://pillow.readthedocs.io/en/stable/_sources/installation/basic-installation.rst.txt Installation of optional Python packages for enhanced image data handling (XMP, FPX, MIC). ```bash python3 -m pip install --upgrade defusedxml olefile ``` -------------------------------- ### Install Linux Prerequisites Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Commands to install necessary development libraries for DNF-based distributions and Alpine Linux. ```bash sudo dnf install libtiff-devel libjpeg-devel openjpeg2-devel zlib-devel \ freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel \ harfbuzz-devel fribidi-devel libraqm-devel libimagequant-devel libxcb-devel ``` ```bash sudo apk add tiff-dev jpeg-dev openjpeg-dev zlib-dev freetype-dev lcms2-dev \ libwebp-dev tcl-dev tk-dev harfbuzz-dev fribidi-dev libimagequant-dev \ libxcb-dev libpng-dev ``` -------------------------------- ### Install build prerequisites on Alpine Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Install development headers for image processing libraries on Alpine Linux. ```bash sudo apk add tiff-dev jpeg-dev openjpeg-dev zlib-dev freetype-dev lcms2-dev \ libwebp-dev tcl-dev tk-dev harfbuzz-dev fribidi-dev libimagequant-dev \ libxcb-dev libpng-dev ``` -------------------------------- ### Install FreeBSD Prerequisites Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Commands to install Python and required development libraries on FreeBSD. ```bash sudo pkg install python3 ``` ```bash sudo pkg install jpeg-turbo tiff webp lcms2 freetype2 openjpeg harfbuzz fribidi libxcb libavif ``` -------------------------------- ### Install optional dependencies Source: https://pillow.readthedocs.io/en/stable/installation/basic-installation.html Install defusedxml and olefile to enable support for XMP data and FPX/MIC image formats respectively. ```bash python3 -m pip install --upgrade defusedxml olefile ``` -------------------------------- ### FreeBSD installation via Packages Source: https://pillow.readthedocs.io/en/stable/_sources/installation/basic-installation.rst.txt Command to install Pillow on FreeBSD using the Packages system. ```bash pkg install py38-pillow ``` -------------------------------- ### Debugging a C extension with GDB Source: https://pillow.readthedocs.io/en/stable/reference/c_extension_debugging.html This example demonstrates starting a Python script within GDB and setting a pending breakpoint in a C source file. ```bash (vpy38-dbg) ubuntu@primary:~/Home/tests$ gdb python GNU gdb (Ubuntu 9.2-0ubuntu1~20.04) 9.2 Copyright (C) 2020 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: . Find the GDB manual and other documentation resources online at: . For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from python... (gdb) b TiffDecode.c:269 No source file named TiffDecode.c. Make breakpoint pending on future shared library load? (y or [n]) y Breakpoint 1 (TiffDecode.c:269) pending. (gdb) r test_tiff.py Starting program: /home/ubuntu/vpy38-dbg/bin/python test_tiff.py [Thread debugging using libthread_db enabled] Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1". /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 16908288 bytes but only got 0. Skipping tag 0 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 67895296 bytes but only got 0. Skipping tag 0 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 1572864 bytes but only got 0. Skipping tag 42 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 116647 bytes but only got 4867. Skipping tag 42738 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 3468830728 bytes but only got 4851. Skipping tag 279 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 2198732800 bytes but only got 0. Skipping tag 0 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 67239937 bytes but only got 4125. Skipping tag 0 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 33947764 bytes but only got 0. Skipping tag 139 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 17170432 bytes but only got 0. Skipping tag 0 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 80478208 bytes but only got 0. Skipping tag 1 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 787460 bytes but only got 4882. Skipping tag 20 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 1075 bytes but only got 0. Skipping tag 256 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 120586240 bytes but only got 0. Skipping tag 194 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 65536 bytes but only got 0. Skipping tag 3 warnings.warn( /home/ubuntu/vpy38-dbg/lib/python3.8/site-packages/Pillow-8.0.1-py3.8-linux-x86_64.egg/PIL/TiffImagePlugin.py:770: UserWarning: Possibly corrupt EXIF data. Expecting to read 198656 bytes but only got 0. Skipping tag 279 warnings.warn( ``` -------------------------------- ### Initialize and Build LUT Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/ImageMorph.html Example of initializing the LutBuilder with a pattern and generating the lookup table. ```python lb = LutBuilder(patterns = ["4:(... .1. 111)->1"]) lut = lb.build_lut() ``` -------------------------------- ### Install libavif build prerequisites on Ubuntu Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Installs build tools required for compiling libavif from source on Ubuntu. ```bash sudo apt-get install cmake ninja-build nasm ``` -------------------------------- ### Install build prerequisites on Red Hat, CentOS, or Fedora Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Install development headers for image processing libraries using the DNF package manager. ```bash sudo dnf install libtiff-devel libjpeg-devel openjpeg2-devel zlib-devel \ freetype-devel lcms2-devel libwebp-devel tcl-devel tk-devel \ harfbuzz-devel fribidi-devel libraqm-devel libimagequant-devel libxcb-devel ``` -------------------------------- ### FreeBSD installation via Ports Source: https://pillow.readthedocs.io/en/stable/_sources/installation/basic-installation.rst.txt Command to install Pillow on FreeBSD using the Ports system. ```bash cd /usr/ports/graphics/py-pillow && make install clean ``` -------------------------------- ### Install Pillow from source Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Commands to upgrade pip and install the package from the current directory. ```bash python3 -m pip install --upgrade pip python3 -m pip install . ``` -------------------------------- ### Install Python development libraries on Alpine Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Install Python development headers and setuptools on Alpine Linux. ```bash sudo apk add python3-dev py3-setuptools ``` -------------------------------- ### Install Python development libraries on Debian or Ubuntu Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Install the necessary Python development headers and setuptools for building from source. ```bash sudo apt-get install python3-dev python3-setuptools ``` -------------------------------- ### Install Pillow from PyPI Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Standard command sequence to install Pillow from source using pip. ```bash python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow --no-binary :all: ``` -------------------------------- ### Install Python development libraries on Fedora Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Install Python development headers and configuration tools on Fedora systems. ```bash sudo dnf install python3-devel redhat-rpm-config ``` -------------------------------- ### Get All Supported Components Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/features.html Returns a list of all supported modules, features, and codecs. ```python def get_supported() -> list[str]: """ :returns: A list of all supported modules, features, and codecs. """ ret = get_supported_modules() ret.extend(get_supported_features()) ret.extend(get_supported_codecs()) return ret ``` -------------------------------- ### Install MSYS2/MinGW Prerequisites Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Commands to install Python, GCC, and required development libraries on MSYS2 MinGW 64-bit. ```bash pacman -S \ mingw-w64-x86_64-gcc \ mingw-w64-x86_64-python \ mingw-w64-x86_64-python-pip \ mingw-w64-x86_64-python-setuptools ``` ```bash pacman -S \ mingw-w64-x86_64-libjpeg-turbo \ mingw-w64-x86_64-zlib \ mingw-w64-x86_64-libtiff \ mingw-w64-x86_64-freetype \ mingw-w64-x86_64-lcms2 \ mingw-w64-x86_64-libwebp \ mingw-w64-x86_64-openjpeg2 \ mingw-w64-x86_64-libimagequant \ mingw-w64-x86_64-libraqm \ mingw-w64-x86_64-libavif ``` -------------------------------- ### Install Python development libraries on Linux Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Commands to install Python development headers and setuptools on Debian, Fedora, and Alpine systems. ```bash sudo apt-get install python3-dev python3-setuptools ``` ```bash sudo dnf install python3-devel redhat-rpm-config ``` ```bash sudo apk add python3-dev py3-setuptools ``` -------------------------------- ### PIL.ImageWin.Dib.query_palette Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/ImageWin.html Installs the palette associated with the image in the given device context. ```APIDOC ## Dib.query_palette(handle) ### Description Installs the palette associated with the image in the given device context. This method should be called upon QUERYNEWPALETTE and PALETTECHANGED events from Windows. If this method returns a non-zero value, one or more display palette entries were changed, and the image should be redrawn. ### Parameters - **handle** (int | HDC | HWND) - Required - Device context (HDC), cast to a Python integer, or an HDC or HWND instance. ``` -------------------------------- ### Print Installation Information Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/features.html Prints detailed information about the current Pillow installation, including module paths and feature support status. ```python def pilinfo(out: IO[str] | None = None, supported_formats: bool = True) -> None: """ Prints information about this installation of Pillow. This function can be called with ``python3 -m PIL``. It can also be called with ``python3 -m PIL.report`` or ``python3 -m PIL --report`` to have "supported_formats" set to ``False``, omitting the list of all supported image file formats. :param out: The output stream to print to. Defaults to ``sys.stdout`` if ``None``. :param supported_formats: If ``True``, a list of all supported image file formats will be printed. """ if out is None: out = sys.stdout Image.init() print("-" * 68, file=out) print(f"Pillow {PIL.__version__}", file=out) py_version_lines = sys.version.splitlines() print(f"Python {py_version_lines[0].strip()}", file=out) for py_version in py_version_lines[1:]: print(f" {py_version.strip()}", file=out) print("-" * 68, file=out) print(f"Python executable is {sys.executable or 'unknown'}", file=out) if sys.prefix != sys.base_prefix: print(f"Environment Python files loaded from {sys.prefix}", file=out) print(f"System Python files loaded from {sys.base_prefix}", file=out) print("-" * 68, file=out) print( f"Python Pillow modules loaded from {os.path.dirname(Image.__file__)}", file=out, ) print( f"Binary Pillow modules loaded from {os.path.dirname(Image.core.__file__)}", file=out, ) print("-" * 68, file=out) for name, feature in [ ("pil", "PIL CORE"), ("tkinter", "TKINTER"), ("freetype2", "FREETYPE2"), ("littlecms2", "LITTLECMS2"), ("webp", "WEBP"), ("avif", "AVIF"), ("jpg", "JPEG"), ("jpg_2000", "OPENJPEG (JPEG2000)"), ("zlib", "ZLIB (PNG/ZIP)"), ("libtiff", "LIBTIFF"), ("raqm", "RAQM (Bidirectional Text)"), ("libimagequant", "LIBIMAGEQUANT (Quantization method)"), ("xcb", "XCB (X protocol)"), ]: if check(name): v: str | None = None if name == "jpg": libjpeg_turbo_version = version_feature("libjpeg_turbo") if libjpeg_turbo_version is not None: v = "mozjpeg" if check_feature("mozjpeg") else "libjpeg-turbo" v += " " + libjpeg_turbo_version if v is None: v = version(name) if v is not None: version_static = name in ("pil", "jpg") if name == "littlecms2": # this check is also in src/_imagingcms.c:setup_module() version_static = tuple(int(x) for x in v.split(".")) < (2, 7) t = "compiled for" if version_static else "loaded" if name == "zlib": zlib_ng_version = version_feature("zlib_ng") if zlib_ng_version is not None: v += ", compiled for zlib-ng " + zlib_ng_version elif name == "raqm": for f in ("fribidi", "harfbuzz"): v2 = version_feature(f) if v2 is not None: v += f", {f} {v2}" print("---", feature, "support ok,", t, v, file=out) else: print("---", feature, "support ok", file=out) else: print("***", feature, "support not installed", file=out) print("-" * 68, file=out) ``` -------------------------------- ### Window.mainloop() Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/ImageWin.html Starts the event loop for the window. ```APIDOC ## Window.mainloop() ### Description Starts the event loop for the window. ``` -------------------------------- ### Get current frame number Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/Image.html Returns the current frame number, starting from 0. ```python def tell(self) -> int: """ Returns the current frame number. See :py:meth:`~PIL.Image.Image.seek`. If defined, :attr:`~PIL.Image.Image.n_frames` refers to the number of available frames. :returns: Frame number, starting with 0. """ return 0 ``` -------------------------------- ### Displaying an image Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt Shows how to display an image using the show() method. ```python >>> im.show() ``` -------------------------------- ### Get XMP Metadata Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/Image.html Returns a dictionary containing XMP tags. Requires the defusedxml library to be installed. ```python def getxmp(self) -> dict[str, Any]: """ Returns a dictionary containing the XMP tags. Requires defusedxml to be installed. :returns: XMP tags in a dictionary. """ def get_name(tag: str) -> str: return re.sub("^{[^}]+}", "", tag) def get_value(element: Element) -> str | dict[str, Any] | None: value: dict[str, Any] = {get_name(k): v for k, v in element.attrib.items()} children = list(element) if children: for child in children: name = get_name(child.tag) child_value = get_value(child) if name in value: if not isinstance(value[name], list): value[name] = [value[name]] value[name].append(child_value) else: value[name] = child_value elif value: if element.text: value["text"] = element.text else: return element.text return value if ElementTree is None: warnings.warn("XMP data cannot be read without defusedxml dependency") return {} if "xmp" not in self.info: return {} root = ElementTree.fromstring(self.info["xmp"].rstrip(b"\x00 ")) return {get_name(root.tag): get_value(root)} ``` -------------------------------- ### Get Current Position Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/TiffImagePlugin.html Returns the current file pointer position relative to the start of the new page. ```python def tell(self) -> int: return self.f.tell() - self.offsetOfNewPage ``` -------------------------------- ### Reading an image from binary data Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt Illustrates how to open an image from binary data using the io.BytesIO class. ```python from PIL import Image import io im = Image.open(io.BytesIO(buffer)) ``` -------------------------------- ### Retrieving matching pixels Source: https://pillow.readthedocs.io/en/stable/_sources/reference/ImageMorph.rst.txt This example demonstrates how to use the match method to get a list of pixels that will be non-empty after an operator is applied, and then verifies the count. ```python coords = mop.match(img) print(coords) # [(17, 1), (18, 1), (34, 1), ...] print(len(coords)) # 550 imgOut = mop.apply(img)[1] print(len(mop.get_on_pixels(imgOut))) # 550 ``` -------------------------------- ### Batch processing with pathlib Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt An alternative to the glob example, using the pathlib module for batch image conversion. ```python from pathlib import Path paths = Path(".").glob("*.png") for path in paths: compress_image(path, path.stem + ".jpg") ``` -------------------------------- ### Install with custom library paths Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Use environment variables to specify non-standard include directories for dependencies. ```bash CFLAGS="-I/usr/pkg/include" python3 -m pip install --upgrade Pillow --no-binary :all: ``` -------------------------------- ### Install Pillow with pip Source: https://pillow.readthedocs.io/en/stable/_sources/installation/basic-installation.rst.txt Standard installation of Pillow using pip, including upgrading pip itself. ```bash python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow ``` -------------------------------- ### Initialize All Format Drivers Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/Image.html Loads all available file format drivers. This is called when preinit is insufficient. ```python def init() -> bool: """ Explicitly initializes the Python Imaging Library. This function loads all available file format drivers. It is called when opening or saving images if :py:meth:`~preinit()` is insufficient, and by :py:meth:`~PIL.features.pilinfo`. """ global _initialized if _initialized >= 2: return False for plugin in _plugins: try: logger.debug("Importing %s", plugin) __import__(f"{__spec__.parent}.{plugin}", globals(), locals(), []) except ImportError as e: # noqa: PERF203 logger.debug("Image: failed to import %s: %s", plugin, e) if OPEN or SAVE: _initialized = 2 return True return False ``` -------------------------------- ### Install Android Dependencies Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Command to install build dependencies within the Termux environment. ```bash pkg install -y python ndk-sysroot clang make \ libjpeg-turbo ``` -------------------------------- ### ImageFileDirectory.__init__ Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/TiffImagePlugin.html Initializes a new ImageFileDirectory instance. To construct from a file, pass the 8-byte magic header. ```APIDOC ## __init__(ifh=b"II\x2a\x00\x00\x00\x00\x00", prefix=None, group=None) ### Description Initializes an ImageFileDirectory. To construct an ImageFileDirectory from a real file, pass the 8-byte magic header to the constructor. To only set the endianness, pass it as the 'prefix' keyword argument. ### Parameters - **ifh** (bytes) - Optional - One of the accepted magic headers; also sets endianness. - **prefix** (bytes) - Optional - Override the endianness of the file. - **group** (int) - Optional - The group identifier. ``` -------------------------------- ### Setup Debug Virtual Environment Source: https://pillow.readthedocs.io/en/stable/_sources/reference/c_extension_debugging.rst.txt Create and activate a virtual environment using a debug Python build to ensure symbols are available. ```bash virtualenv -p python3.8-dbg ~/vpy38-dbg source ~/vpy38-dbg/bin/activate cd ~/Pillow && make install ``` -------------------------------- ### Install Pillow via pip Source: https://pillow.readthedocs.io/en/stable/installation/basic-installation.html Standard command to upgrade pip and install the Pillow package. ```bash python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow ``` -------------------------------- ### macOS universal binary creation Source: https://pillow.readthedocs.io/en/stable/_sources/installation/basic-installation.rst.txt Steps to download and combine x86-64 and arm64 Pillow binaries into a universal2 wheel on macOS. ```bash python3 -m pip download --only-binary=:all: --platform macosx_10_10_x86_64 Pillow python3 -m pip download --only-binary=:all: --platform macosx_11_0_arm64 Pillow python3 -m pip install delocate ``` -------------------------------- ### Install Pillow prerequisites on FreeBSD Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Installs required image processing libraries for FreeBSD 10 or 11. ```bash sudo pkg install jpeg-turbo tiff webp lcms2 freetype2 openjpeg harfbuzz fribidi libxcb libavif ``` -------------------------------- ### Loading an image from a file Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt Demonstrates how to open an image file using Image.open() and access its properties. ```python >>> from PIL import Image >>> im = Image.open("hopper.ppm") ``` -------------------------------- ### Resizing and rotating an image Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt Examples of resizing an image to a specific dimension and rotating an image by a given angle in degrees counter-clockwise. ```python out = im.resize((128, 128)) out = im.rotate(45) # degrees counter-clockwise ``` -------------------------------- ### Install Pillow prerequisites on MSYS2 Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Installs the necessary image processing libraries for the 64-bit MSYS2 environment. ```bash pacman -S \ mingw-w64-x86_64-libjpeg-turbo \ mingw-w64-x86_64-zlib \ mingw-w64-x86_64-libtiff \ mingw-w64-x86_64-freetype \ mingw-w64-x86_64-lcms2 \ mingw-w64-x86_64-libwebp \ mingw-w64-x86_64-openjpeg2 \ mingw-w64-x86_64-libimagequant \ mingw-w64-x86_64-libraqm \ mingw-w64-x86_64-libavif ``` -------------------------------- ### Install Pillow on FreeBSD via Packages Source: https://pillow.readthedocs.io/en/stable/installation/basic-installation.html Install the pre-compiled Pillow package using the pkg manager. ```bash pkg install py38-pillow ``` -------------------------------- ### Reading an image from a URL Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt Demonstrates opening an image directly from a URL. ```python from PIL import Image from urllib.request import urlopen url = "https://python-pillow.github.io/assets/images/pillow-logo.png" img = Image.open(urlopen(url)) ``` -------------------------------- ### Install Pillow on FreeBSD via Ports Source: https://pillow.readthedocs.io/en/stable/installation/basic-installation.html Build and install Pillow using the FreeBSD ports system. ```bash cd /usr/ports/graphics/py-pillow && make install clean ``` -------------------------------- ### ImageFileDirectory dispatch setup Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/TiffImagePlugin.html Dynamically setting up load and write dispatch methods for TIFF tags. ```python ImageFileDirectory_v2._load_dispatch = _load_dispatch ImageFileDirectory_v2._write_dispatch = _write_dispatch for idx, name in TYPES.items(): name = name.replace(" ", "_") setattr(ImageFileDirectory_v2, f"load_{name}", _load_dispatch[idx][1]) setattr(ImageFileDirectory_v2, f"write_{name}", _write_dispatch[idx]) del _load_dispatch, _write_dispatch, idx, name ``` -------------------------------- ### Install olefile package Source: https://pillow.readthedocs.io/en/stable/_sources/deprecations.rst.txt Use this command to install the standalone olefile package after the removal of PIL.OleFileIO from Pillow. ```bash python3 -m pip install olefile ``` -------------------------------- ### Drawing PostScript Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt This snippet demonstrates how to create a PostScript file, draw text and an image onto it using the PSDraw module. ```python from PIL import Image, PSDraw import os # Define the PostScript file ps_file = open("hopper.ps", "wb") # Create a PSDraw object ps = PSDraw.PSDraw(ps_file) # Start the document ps.begin_document() # Set the text to be drawn text = "Hopper" # Define the PostScript font font_name = "Helvetica-Narrow-Bold" font_size = 36 # Calculate text size (approximation as PSDraw doesn't provide direct method) # Assuming average character width as 0.6 of the font size text_width = len(text) * font_size * 0.6 text_height = font_size # Set the position (top-center) page_width, page_height = 595, 842 # A4 size in points text_x = (page_width - text_width) // 2 text_y = page_height - text_height - 50 # Distance from the top of the page # Load the image image_path = "hopper.ppm" # Update this with your image path with Image.open(image_path) as im: # Resize the image if it's too large im.thumbnail((page_width - 100, page_height // 2)) # Define the box where the image will be placed img_x = (page_width - im.width) // 2 img_y = text_y + text_height - 200 # 200 points below the text # Draw the image (75 dpi) ps.image((img_x, img_y, img_x + im.width, img_y + im.height), im, 75) # Draw the text ps.setfont(font_name, font_size) ps.text((text_x, text_y), text) # End the document ps.end_document() ps_file.close() ``` -------------------------------- ### Opening an image from a file Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt Demonstrates how to open an image file using Pillow. ```python from PIL import Image with Image.open("hopper.ppm") as im: ... ``` -------------------------------- ### Applying a point transform for contrast manipulation Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt Illustrates using the Image.point method with a lambda function to modify pixel values, such as increasing contrast. ```python # multiply each pixel by 20 out = im.point(lambda i: i * 20) ``` -------------------------------- ### Create JPEG thumbnails Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt A script to create JPEG thumbnails of a specified size for given image files. ```python import os, sys from PIL import Image size = (128, 128) for infile in sys.argv[1:]: outfile = os.path.splitext(infile)[0] + ".thumbnail" if infile != outfile: try: with Image.open(infile) as im: im.thumbnail(size) im.save(outfile, "JPEG") except OSError: print("cannot create thumbnail for", infile) ``` -------------------------------- ### Install macOS Dependencies Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Commands to install external libraries and build dependencies for libavif on macOS using Homebrew. ```bash brew install libavif libjpeg libraqm libtiff little-cms2 openjpeg webp ``` ```bash brew install aom dav1d rav1e svt-av1 ``` -------------------------------- ### Example Usage Source: https://pillow.readthedocs.io/en/stable/_sources/reference/ImageText.rst.txt This example demonstrates how to create a Text object, apply styling, and then measure or draw it. ```python from PIL import Image, ImageDraw, ImageFont, ImageText font = ImageFont.truetype("Tests/fonts/FreeMono.ttf", 24) text = ImageText.Text("Hello world", font) text.embed_color() text.stroke(2, "#0f0") print(text.get_length()) # 154.0 print(text.get_bbox()) # (-2, 3, 156, 22) im = Image.new("RGB", text.get_bbox()[2:]) d = ImageDraw.Draw(im) d.text((0, 0), text, "#f00") ``` -------------------------------- ### Applying a detail filter Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt Demonstrates applying a pre-defined enhancement filter (ImageFilter.DETAIL) to an image using the Image.filter method. ```python from PIL import ImageFilter out = im.filter(ImageFilter.DETAIL) ``` -------------------------------- ### Install Python and GCC on MSYS2 Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Sets up the base environment for building Pillow on Windows using MSYS2. ```bash pacman -S \ mingw-w64-x86_64-gcc \ mingw-w64-x86_64-python \ mingw-w64-x86_64-python-pip \ mingw-w64-x86_64-python-setuptools ``` -------------------------------- ### Tkinter example Source: https://pillow.readthedocs.io/en/stable/_sources/reference/ImageWin.rst.txt Example of using ImageWin with Tkinter to display an image on a Windows device context. ```python from PIL import ImageWin dib = ImageWin.Dib(...) hwnd = ImageWin.HWND(widget.winfo_id()) dib.draw(hwnd, xy) ``` -------------------------------- ### GimpGradientFile.__init__ Source: https://pillow.readthedocs.io/en/stable/_modules/PIL/GimpGradientFile.html Initializes a new GimpGradientFile instance by reading from a file-like object containing GIMP gradient data. ```APIDOC ## GimpGradientFile(fp) ### Description Initializes the GimpGradientFile handler by parsing the provided file object. It validates the file format and populates the internal gradient segments. ### Parameters - **fp** (IO[bytes]) - Required - A file-like object opened in binary mode containing the GIMP gradient data. ### Errors - **SyntaxError**: Raised if the file does not start with the 'GIMP Gradient' header. - **OSError**: Raised if the gradient uses an unsupported color space (e.g., HSV). ``` -------------------------------- ### Install external libraries on macOS via Homebrew Source: https://pillow.readthedocs.io/en/stable/installation/building-from-source.html Installs common image processing libraries required for Pillow on macOS. ```bash brew install libavif libjpeg libraqm libtiff little-cms2 openjpeg webp ``` -------------------------------- ### Convert files to JPEG Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt A script to convert all files provided as command-line arguments to JPEG format. ```python import os, sys from PIL import Image for infile in sys.argv[1:]: f, e = os.path.splitext(infile) outfile = f + ".jpg" if infile != outfile: try: with Image.open(infile) as im: im.save(outfile) except OSError: print("cannot convert", infile) ``` -------------------------------- ### Install Pillow build prerequisites on Ubuntu Source: https://pillow.readthedocs.io/en/stable/_sources/installation/building-from-source.rst.txt Installs common development libraries required for Pillow features on Ubuntu systems. ```bash sudo apt-get install libtiff5-dev libjpeg8-dev libopenjp2-7-dev zlib1g-dev \ libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python3-tk \ libharfbuzz-dev libfribidi-dev libxcb1-dev ``` -------------------------------- ### Enhancing images Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt This snippet demonstrates how to enhance an image using the ImageEnhance module, specifically adjusting contrast. ```python from PIL import ImageEnhance enh = ImageEnhance.Contrast(im) enh.enhance(1.3).show("30% more contrast") ``` -------------------------------- ### Batch processing: Converting PNG to JPEG Source: https://pillow.readthedocs.io/en/stable/_sources/handbook/tutorial.rst.txt An example of batch processing, converting all PNG images in a directory to JPEGs with optimized quality. ```python import glob from PIL import Image def compress_image(source_path: str, dest_path: str) -> None: with Image.open(source_path) as img: if img.mode != "RGB": img = img.convert("RGB") img.save(dest_path, "JPEG", optimize=True, quality=80) paths = glob.glob("*.png") for path in paths: compress_image(path, path[:-4] + ".jpg") ```