Skip to content

Commit

Permalink
Merge pull request #5862 from kolibril13/pathlib
Browse files Browse the repository at this point in the history
Added PIL + pathlib Tutorial
  • Loading branch information
mergify[bot] committed Dec 19, 2021
2 parents 0badf97 + a12c186 commit 591e79e
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions docs/handbook/tutorial.rst
Expand Up @@ -497,6 +497,43 @@ Reading from a tar archive
fp = TarIO.TarIO("Tests/images/hopper.tar", "hopper.jpg")
im = Image.open(fp)


Batch processing
^^^^^^^^^^^^^^^^

Operations can be applied to multiple image files. For example, all PNG images
in the current directory can be saved as JPEGs at reduced quality.

::

import glob
from PIL import Image


def compress_image(source_path, dest_path):
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")

Since images can also be opened from a ``Path`` from the ``pathlib`` module,
the example could be modified to use ``pathlib`` instead of the ``glob``
module.

::

from pathlib import Path

paths = Path(".").glob("*.png")
for path in paths:
compress_image(path, path.stem + ".jpg")


Controlling the decoder
-----------------------

Expand Down

0 comments on commit 591e79e

Please sign in to comment.