2013-10-07 04:30:20 +04:00
|
|
|
|
Tutorial
|
|
|
|
|
========
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
Using the Image class
|
|
|
|
|
---------------------
|
|
|
|
|
|
|
|
|
|
The most important class in the Python Imaging Library is the
|
|
|
|
|
:py:class:`~PIL.Image.Image` class, defined in the module with the same name.
|
|
|
|
|
You can create instances of this class in several ways; either by loading
|
|
|
|
|
images from files, processing other images, or creating images from scratch.
|
|
|
|
|
|
|
|
|
|
To load an image from a file, use the :py:func:`~PIL.Image.open` function
|
|
|
|
|
in the :py:mod:`~PIL.Image` module::
|
|
|
|
|
|
|
|
|
|
>>> from PIL import Image
|
2017-05-06 16:20:34 +03:00
|
|
|
|
>>> im = Image.open("hopper.ppm")
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2013-10-07 07:36:31 +04:00
|
|
|
|
If successful, this function returns an :py:class:`~PIL.Image.Image` object.
|
|
|
|
|
You can now use instance attributes to examine the file contents::
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2013-10-07 09:54:39 +04:00
|
|
|
|
>>> print(im.format, im.size, im.mode)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
PPM (512, 512) RGB
|
|
|
|
|
|
|
|
|
|
The :py:attr:`~PIL.Image.Image.format` attribute identifies the source of an
|
|
|
|
|
image. If the image was not read from a file, it is set to None. The size
|
|
|
|
|
attribute is a 2-tuple containing width and height (in pixels). The
|
|
|
|
|
:py:attr:`~PIL.Image.Image.mode` attribute defines the number and names of the
|
|
|
|
|
bands in the image, and also the pixel type and depth. Common modes are “L”
|
2023-10-19 11:12:01 +03:00
|
|
|
|
(luminance) for grayscale images, “RGB” for true color images, and “CMYK” for
|
2013-10-07 05:12:39 +04:00
|
|
|
|
pre-press images.
|
|
|
|
|
|
2020-04-07 09:58:21 +03:00
|
|
|
|
If the file cannot be opened, an :py:exc:`OSError` exception is raised.
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
Once you have an instance of the :py:class:`~PIL.Image.Image` class, you can use
|
|
|
|
|
the methods defined by this class to process and manipulate the image. For
|
|
|
|
|
example, let’s display the image we just loaded::
|
|
|
|
|
|
|
|
|
|
>>> im.show()
|
|
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
|
|
The standard version of :py:meth:`~PIL.Image.Image.show` is not very
|
2018-09-29 08:07:59 +03:00
|
|
|
|
efficient, since it saves the image to a temporary file and calls a utility
|
|
|
|
|
to display the image. If you don’t have an appropriate utility installed,
|
|
|
|
|
it won’t even work. When it does work though, it is very handy for
|
|
|
|
|
debugging and tests.
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
The following sections provide an overview of the different functions provided in this library.
|
|
|
|
|
|
|
|
|
|
Reading and writing images
|
|
|
|
|
--------------------------
|
|
|
|
|
|
|
|
|
|
The Python Imaging Library supports a wide variety of image file formats. To
|
|
|
|
|
read files from disk, use the :py:func:`~PIL.Image.open` function in the
|
|
|
|
|
:py:mod:`~PIL.Image` module. You don’t have to know the file format to open a
|
|
|
|
|
file. The library automatically determines the format based on the contents of
|
|
|
|
|
the file.
|
|
|
|
|
|
|
|
|
|
To save a file, use the :py:meth:`~PIL.Image.Image.save` method of the
|
|
|
|
|
:py:class:`~PIL.Image.Image` class. When saving files, the name becomes
|
|
|
|
|
important. Unless you specify the format, the library uses the filename
|
|
|
|
|
extension to discover which file storage format to use.
|
|
|
|
|
|
|
|
|
|
Convert files to JPEG
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
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:
|
2020-02-29 02:29:44 +03:00
|
|
|
|
with Image.open(infile) as im:
|
|
|
|
|
im.save(outfile)
|
2020-04-07 09:58:21 +03:00
|
|
|
|
except OSError:
|
2013-10-07 09:54:39 +04:00
|
|
|
|
print("cannot convert", infile)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
A second argument can be supplied to the :py:meth:`~PIL.Image.Image.save`
|
|
|
|
|
method which explicitly specifies a file format. If you use a non-standard
|
|
|
|
|
extension, you must always specify the format this way:
|
|
|
|
|
|
|
|
|
|
Create JPEG thumbnails
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
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:
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
with Image.open(infile) as im:
|
|
|
|
|
im.thumbnail(size)
|
|
|
|
|
im.save(outfile, "JPEG")
|
2020-04-07 09:58:21 +03:00
|
|
|
|
except OSError:
|
2013-10-07 09:54:39 +04:00
|
|
|
|
print("cannot create thumbnail for", infile)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
It is important to note that the library doesn’t decode or load the raster data
|
|
|
|
|
unless it really has to. When you open a file, the file header is read to
|
|
|
|
|
determine the file format and extract things like mode, size, and other
|
|
|
|
|
properties required to decode the file, but the rest of the file is not
|
|
|
|
|
processed until later.
|
|
|
|
|
|
|
|
|
|
This means that opening an image file is a fast operation, which is independent
|
|
|
|
|
of the file size and compression type. Here’s a simple script to quickly
|
|
|
|
|
identify a set of image files:
|
|
|
|
|
|
|
|
|
|
Identify Image Files
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
import sys
|
|
|
|
|
from PIL import Image
|
|
|
|
|
|
|
|
|
|
for infile in sys.argv[1:]:
|
|
|
|
|
try:
|
2014-04-18 08:53:49 +04:00
|
|
|
|
with Image.open(infile) as im:
|
2020-07-16 12:43:29 +03:00
|
|
|
|
print(infile, im.format, f"{im.size}x{im.mode}")
|
2020-04-07 09:58:21 +03:00
|
|
|
|
except OSError:
|
2013-10-07 05:12:39 +04:00
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
Cutting, pasting, and merging images
|
|
|
|
|
------------------------------------
|
|
|
|
|
|
|
|
|
|
The :py:class:`~PIL.Image.Image` class contains methods allowing you to
|
|
|
|
|
manipulate regions within an image. To extract a sub-rectangle from an image,
|
|
|
|
|
use the :py:meth:`~PIL.Image.Image.crop` method.
|
|
|
|
|
|
|
|
|
|
Copying a subrectangle from an image
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
box = (100, 100, 400, 400)
|
|
|
|
|
region = im.crop(box)
|
|
|
|
|
|
|
|
|
|
The region is defined by a 4-tuple, where coordinates are (left, upper, right,
|
|
|
|
|
lower). The Python Imaging Library uses a coordinate system with (0, 0) in the
|
|
|
|
|
upper left corner. Also note that coordinates refer to positions between the
|
|
|
|
|
pixels, so the region in the above example is exactly 300x300 pixels.
|
|
|
|
|
|
|
|
|
|
The region could now be processed in a certain manner and pasted back.
|
|
|
|
|
|
|
|
|
|
Processing a subrectangle, and pasting it back
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
|
region = region.transpose(Image.Transpose.ROTATE_180)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
im.paste(region, box)
|
|
|
|
|
|
|
|
|
|
When pasting regions back, the size of the region must match the given region
|
|
|
|
|
exactly. In addition, the region cannot extend outside the image. However, the
|
|
|
|
|
modes of the original image and the region do not need to match. If they don’t,
|
|
|
|
|
the region is automatically converted before being pasted (see the section on
|
|
|
|
|
:ref:`color-transforms` below for details).
|
|
|
|
|
|
|
|
|
|
Here’s an additional example:
|
|
|
|
|
|
|
|
|
|
Rolling an image
|
|
|
|
|
^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
2022-03-12 08:17:56 +03:00
|
|
|
|
def roll(im, delta):
|
2018-01-12 12:46:16 +03:00
|
|
|
|
"""Roll an image sideways."""
|
2022-03-12 08:17:56 +03:00
|
|
|
|
xsize, ysize = im.size
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
delta = delta % xsize
|
2021-12-03 23:50:08 +03:00
|
|
|
|
if delta == 0:
|
2022-03-12 08:17:56 +03:00
|
|
|
|
return im
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2022-03-12 08:17:56 +03:00
|
|
|
|
part1 = im.crop((0, 0, delta, ysize))
|
|
|
|
|
part2 = im.crop((delta, 0, xsize, ysize))
|
|
|
|
|
im.paste(part1, (xsize - delta, 0, xsize, ysize))
|
|
|
|
|
im.paste(part2, (0, 0, xsize - delta, ysize))
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2022-03-12 08:17:56 +03:00
|
|
|
|
return im
|
|
|
|
|
|
|
|
|
|
Or if you would like to merge two images into a wider image:
|
|
|
|
|
|
|
|
|
|
Merging images
|
|
|
|
|
^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
def merge(im1, im2):
|
|
|
|
|
w = im1.size[0] + im2.size[0]
|
|
|
|
|
h = max(im1.size[1], im2.size[1])
|
|
|
|
|
im = Image.new("RGBA", (w, h))
|
|
|
|
|
|
|
|
|
|
im.paste(im1)
|
|
|
|
|
im.paste(im2, (im1.size[0], 0))
|
|
|
|
|
|
|
|
|
|
return im
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
For more advanced tricks, the paste method can also take a transparency mask as
|
|
|
|
|
an optional argument. In this mask, the value 255 indicates that the pasted
|
|
|
|
|
image is opaque in that position (that is, the pasted image should be used as
|
|
|
|
|
is). The value 0 means that the pasted image is completely transparent. Values
|
2015-08-24 04:30:39 +03:00
|
|
|
|
in-between indicate different levels of transparency. For example, pasting an
|
|
|
|
|
RGBA image and also using it as the mask would paste the opaque portion
|
|
|
|
|
of the image but not its transparent background.
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
The Python Imaging Library also allows you to work with the individual bands of
|
|
|
|
|
an multi-band image, such as an RGB image. The split method creates a set of
|
|
|
|
|
new images, each containing one band from the original multi-band image. The
|
|
|
|
|
merge function takes a mode and a tuple of images, and combines them into a new
|
|
|
|
|
image. The following sample swaps the three bands of an RGB image:
|
|
|
|
|
|
|
|
|
|
Splitting and merging bands
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
r, g, b = im.split()
|
|
|
|
|
im = Image.merge("RGB", (b, g, r))
|
|
|
|
|
|
|
|
|
|
Note that for a single-band image, :py:meth:`~PIL.Image.Image.split` returns
|
2013-10-07 05:19:56 +04:00
|
|
|
|
the image itself. To work with individual color bands, you may want to convert
|
2013-10-07 05:12:39 +04:00
|
|
|
|
the image to “RGB” first.
|
|
|
|
|
|
|
|
|
|
Geometrical transforms
|
|
|
|
|
----------------------
|
|
|
|
|
|
|
|
|
|
The :py:class:`PIL.Image.Image` class contains methods to
|
|
|
|
|
:py:meth:`~PIL.Image.Image.resize` and :py:meth:`~PIL.Image.Image.rotate` an
|
|
|
|
|
image. The former takes a tuple giving the new size, the latter the angle in
|
|
|
|
|
degrees counter-clockwise.
|
|
|
|
|
|
|
|
|
|
Simple geometry transforms
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
out = im.resize((128, 128))
|
|
|
|
|
out = im.rotate(45) # degrees counter-clockwise
|
|
|
|
|
|
|
|
|
|
To rotate the image in 90 degree steps, you can either use the
|
|
|
|
|
:py:meth:`~PIL.Image.Image.rotate` method or the
|
|
|
|
|
:py:meth:`~PIL.Image.Image.transpose` method. The latter can also be used to
|
|
|
|
|
flip an image around its horizontal or vertical axis.
|
|
|
|
|
|
|
|
|
|
Transposing an image
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
2022-01-15 01:02:31 +03:00
|
|
|
|
out = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
|
|
|
|
|
out = im.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
|
|
|
|
|
out = im.transpose(Image.Transpose.ROTATE_90)
|
|
|
|
|
out = im.transpose(Image.Transpose.ROTATE_180)
|
|
|
|
|
out = im.transpose(Image.Transpose.ROTATE_270)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2016-02-28 15:29:12 +03:00
|
|
|
|
``transpose(ROTATE)`` operations can also be performed identically with
|
2019-09-05 23:49:31 +03:00
|
|
|
|
:py:meth:`~PIL.Image.Image.rotate` operations, provided the ``expand`` flag is
|
2016-02-28 15:29:12 +03:00
|
|
|
|
true, to provide for the same changes to the image's size.
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
A more general form of image transformations can be carried out via the
|
|
|
|
|
:py:meth:`~PIL.Image.Image.transform` method.
|
|
|
|
|
|
2023-09-28 01:27:56 +03:00
|
|
|
|
Relative resizing
|
|
|
|
|
^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
Instead of calculating the size of the new image when resizing, you can also
|
|
|
|
|
choose to resize relative to a given size.
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
from PIL import Image, ImageOps
|
|
|
|
|
size = (100, 150)
|
2024-04-10 16:37:38 +03:00
|
|
|
|
with Image.open("Tests/images/hopper.webp") as im:
|
|
|
|
|
ImageOps.contain(im, size).save("imageops_contain.webp")
|
|
|
|
|
ImageOps.cover(im, size).save("imageops_cover.webp")
|
|
|
|
|
ImageOps.fit(im, size).save("imageops_fit.webp")
|
|
|
|
|
ImageOps.pad(im, size, color="#f00").save("imageops_pad.webp")
|
2023-09-28 01:27:56 +03:00
|
|
|
|
|
|
|
|
|
# thumbnail() can also be used,
|
|
|
|
|
# but will modify the image object in place
|
|
|
|
|
im.thumbnail(size)
|
2024-04-10 16:37:38 +03:00
|
|
|
|
im.save("image_thumbnail.webp")
|
|
|
|
|
|
|
|
|
|
+----------------+--------------------------------------------+---------------------------------------------+-------------------------------------------+-----------------------------------------+-----------------------------------------+
|
|
|
|
|
| | :py:meth:`~PIL.Image.Image.thumbnail` | :py:meth:`~PIL.ImageOps.contain` | :py:meth:`~PIL.ImageOps.cover` | :py:meth:`~PIL.ImageOps.fit` | :py:meth:`~PIL.ImageOps.pad` |
|
|
|
|
|
+================+============================================+=============================================+===========================================+=========================================+=========================================+
|
|
|
|
|
|Given size | ``(100, 150)`` | ``(100, 150)`` | ``(100, 150)`` | ``(100, 150)`` | ``(100, 150)`` |
|
|
|
|
|
+----------------+--------------------------------------------+---------------------------------------------+-------------------------------------------+-----------------------------------------+-----------------------------------------+
|
|
|
|
|
|Resulting image | .. image:: ../example/image_thumbnail.webp | .. image:: ../example/imageops_contain.webp | .. image:: ../example/imageops_cover.webp | .. image:: ../example/imageops_fit.webp | .. image:: ../example/imageops_pad.webp |
|
|
|
|
|
+----------------+--------------------------------------------+---------------------------------------------+-------------------------------------------+-----------------------------------------+-----------------------------------------+
|
|
|
|
|
|Resulting size | ``100×100`` | ``100×100`` | ``150×150`` | ``100×150`` | ``100×150`` |
|
|
|
|
|
+----------------+--------------------------------------------+---------------------------------------------+-------------------------------------------+-----------------------------------------+-----------------------------------------+
|
2023-09-28 01:27:56 +03:00
|
|
|
|
|
2013-10-07 05:12:39 +04:00
|
|
|
|
.. _color-transforms:
|
|
|
|
|
|
|
|
|
|
Color transforms
|
|
|
|
|
----------------
|
|
|
|
|
|
|
|
|
|
The Python Imaging Library allows you to convert images between different pixel
|
|
|
|
|
representations using the :py:meth:`~PIL.Image.Image.convert` method.
|
|
|
|
|
|
|
|
|
|
Converting between modes
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
2017-05-29 12:41:30 +03:00
|
|
|
|
from PIL import Image
|
2021-12-03 23:50:08 +03:00
|
|
|
|
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
with Image.open("hopper.ppm") as im:
|
|
|
|
|
im = im.convert("L")
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
The library supports transformations between each supported mode and the “L”
|
|
|
|
|
and “RGB” modes. To convert between other modes, you may have to use an
|
|
|
|
|
intermediate image (typically an “RGB” image).
|
|
|
|
|
|
|
|
|
|
Image enhancement
|
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
|
|
The Python Imaging Library provides a number of methods and modules that can be
|
|
|
|
|
used to enhance images.
|
|
|
|
|
|
|
|
|
|
Filters
|
|
|
|
|
^^^^^^^
|
|
|
|
|
|
|
|
|
|
The :py:mod:`~PIL.ImageFilter` module contains a number of pre-defined
|
|
|
|
|
enhancement filters that can be used with the
|
|
|
|
|
:py:meth:`~PIL.Image.Image.filter` method.
|
|
|
|
|
|
|
|
|
|
Applying filters
|
|
|
|
|
~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
from PIL import ImageFilter
|
|
|
|
|
out = im.filter(ImageFilter.DETAIL)
|
|
|
|
|
|
|
|
|
|
Point Operations
|
|
|
|
|
^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
The :py:meth:`~PIL.Image.Image.point` method can be used to translate the pixel
|
|
|
|
|
values of an image (e.g. image contrast manipulation). In most cases, a
|
2014-10-03 19:00:50 +04:00
|
|
|
|
function object expecting one argument can be passed to this method. Each
|
2013-10-07 05:12:39 +04:00
|
|
|
|
pixel is processed according to that function:
|
|
|
|
|
|
|
|
|
|
Applying point transforms
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
# multiply each pixel by 1.2
|
|
|
|
|
out = im.point(lambda i: i * 1.2)
|
|
|
|
|
|
|
|
|
|
Using the above technique, you can quickly apply any simple expression to an
|
|
|
|
|
image. You can also combine the :py:meth:`~PIL.Image.Image.point` and
|
|
|
|
|
:py:meth:`~PIL.Image.Image.paste` methods to selectively modify an image:
|
|
|
|
|
|
|
|
|
|
Processing individual bands
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
# split the image into individual bands
|
|
|
|
|
source = im.split()
|
|
|
|
|
|
|
|
|
|
R, G, B = 0, 1, 2
|
|
|
|
|
|
|
|
|
|
# select regions where red is less than 100
|
|
|
|
|
mask = source[R].point(lambda i: i < 100 and 255)
|
|
|
|
|
|
|
|
|
|
# process the green band
|
|
|
|
|
out = source[G].point(lambda i: i * 0.7)
|
|
|
|
|
|
|
|
|
|
# paste the processed band back, but only where red was < 100
|
|
|
|
|
source[G].paste(out, None, mask)
|
|
|
|
|
|
|
|
|
|
# build a new multiband image
|
|
|
|
|
im = Image.merge(im.mode, source)
|
|
|
|
|
|
|
|
|
|
Note the syntax used to create the mask::
|
|
|
|
|
|
|
|
|
|
imout = im.point(lambda i: expression and 255)
|
|
|
|
|
|
|
|
|
|
Python only evaluates the portion of a logical expression as is necessary to
|
|
|
|
|
determine the outcome, and returns the last value examined as the result of the
|
|
|
|
|
expression. So if the expression above is false (0), Python does not look at
|
|
|
|
|
the second operand, and thus returns 0. Otherwise, it returns 255.
|
|
|
|
|
|
|
|
|
|
Enhancement
|
|
|
|
|
^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
For more advanced image enhancement, you can use the classes in the
|
|
|
|
|
:py:mod:`~PIL.ImageEnhance` module. Once created from an image, an enhancement
|
|
|
|
|
object can be used to quickly try out different settings.
|
|
|
|
|
|
2013-10-07 05:19:56 +04:00
|
|
|
|
You can adjust contrast, brightness, color balance and sharpness in this way.
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
Enhancing images
|
|
|
|
|
~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
from PIL import ImageEnhance
|
|
|
|
|
|
|
|
|
|
enh = ImageEnhance.Contrast(im)
|
|
|
|
|
enh.enhance(1.3).show("30% more contrast")
|
|
|
|
|
|
|
|
|
|
Image sequences
|
|
|
|
|
---------------
|
|
|
|
|
|
|
|
|
|
The Python Imaging Library contains some basic support for image sequences
|
|
|
|
|
(also called animation formats). Supported sequence formats include FLI/FLC,
|
|
|
|
|
GIF, and a few experimental formats. TIFF files can also contain more than one
|
|
|
|
|
frame.
|
|
|
|
|
|
|
|
|
|
When you open a sequence file, PIL automatically loads the first frame in the
|
|
|
|
|
sequence. You can use the seek and tell methods to move between different
|
|
|
|
|
frames:
|
|
|
|
|
|
|
|
|
|
Reading sequences
|
|
|
|
|
^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
from PIL import Image
|
|
|
|
|
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
with Image.open("animation.gif") as im:
|
2021-12-03 23:50:08 +03:00
|
|
|
|
im.seek(1) # skip to the second frame
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
try:
|
|
|
|
|
while 1:
|
2021-12-03 23:50:08 +03:00
|
|
|
|
im.seek(im.tell() + 1)
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
# do something to im
|
|
|
|
|
except EOFError:
|
2021-12-03 23:50:08 +03:00
|
|
|
|
pass # end of sequence
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
As seen in this example, you’ll get an :py:exc:`EOFError` exception when the
|
|
|
|
|
sequence ends.
|
|
|
|
|
|
2016-04-16 04:43:28 +03:00
|
|
|
|
The following class lets you use the for-statement to loop over the sequence:
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2016-04-16 04:43:28 +03:00
|
|
|
|
Using the ImageSequence Iterator class
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
2016-04-16 04:43:28 +03:00
|
|
|
|
from PIL import ImageSequence
|
|
|
|
|
for frame in ImageSequence.Iterator(im):
|
2013-10-07 05:12:39 +04:00
|
|
|
|
# ...do something to frame...
|
|
|
|
|
|
|
|
|
|
|
2020-07-10 11:48:02 +03:00
|
|
|
|
PostScript printing
|
2013-10-07 05:12:39 +04:00
|
|
|
|
-------------------
|
|
|
|
|
|
|
|
|
|
The Python Imaging Library includes functions to print images, text and
|
2020-07-10 11:48:02 +03:00
|
|
|
|
graphics on PostScript printers. Here’s a simple example:
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2020-07-10 11:48:02 +03:00
|
|
|
|
Drawing PostScript
|
2013-10-07 05:12:39 +04:00
|
|
|
|
^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
from PIL import Image
|
|
|
|
|
from PIL import PSDraw
|
|
|
|
|
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
with Image.open("hopper.ppm") as im:
|
|
|
|
|
title = "hopper"
|
2021-12-03 23:50:08 +03:00
|
|
|
|
box = (1 * 72, 2 * 72, 7 * 72, 10 * 72) # in points
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2021-12-03 23:50:08 +03:00
|
|
|
|
ps = PSDraw.PSDraw() # default is sys.stdout or sys.stdout.buffer
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
ps.begin_document(title)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
# draw the image (75 dpi)
|
|
|
|
|
ps.image(box, im, 75)
|
|
|
|
|
ps.rectangle(box)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
# draw title
|
|
|
|
|
ps.setfont("HelveticaNarrow-Bold", 36)
|
2021-12-03 23:50:08 +03:00
|
|
|
|
ps.text((3 * 72, 4 * 72), title)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
ps.end_document()
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
More on reading images
|
|
|
|
|
----------------------
|
|
|
|
|
|
|
|
|
|
As described earlier, the :py:func:`~PIL.Image.open` function of the
|
|
|
|
|
:py:mod:`~PIL.Image` module is used to open an image file. In most cases, you
|
2020-02-06 12:10:34 +03:00
|
|
|
|
simply pass it the filename as an argument. ``Image.open()`` can be used as a
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
context manager::
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2017-05-29 12:41:30 +03:00
|
|
|
|
from PIL import Image
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
with Image.open("hopper.ppm") as im:
|
|
|
|
|
...
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
If everything goes well, the result is an :py:class:`PIL.Image.Image` object.
|
2020-04-07 09:58:21 +03:00
|
|
|
|
Otherwise, an :exc:`OSError` exception is raised.
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
You can use a file-like object instead of the filename. The object must
|
2020-07-09 20:48:04 +03:00
|
|
|
|
implement ``file.read``, ``file.seek`` and ``file.tell`` methods,
|
|
|
|
|
and be opened in binary mode.
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
Reading from an open file
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
2017-05-29 12:41:30 +03:00
|
|
|
|
from PIL import Image
|
2021-12-03 23:50:08 +03:00
|
|
|
|
|
2017-05-29 12:41:48 +03:00
|
|
|
|
with open("hopper.ppm", "rb") as fp:
|
|
|
|
|
im = Image.open(fp)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2020-01-21 15:21:57 +03:00
|
|
|
|
To read an image from binary data, use the :py:class:`~io.BytesIO`
|
2013-10-07 05:12:39 +04:00
|
|
|
|
class:
|
|
|
|
|
|
2020-01-21 15:21:57 +03:00
|
|
|
|
Reading from binary data
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
2019-05-06 01:38:43 +03:00
|
|
|
|
from PIL import Image
|
2020-01-21 15:21:57 +03:00
|
|
|
|
import io
|
2021-12-03 23:50:08 +03:00
|
|
|
|
|
2020-01-21 15:21:57 +03:00
|
|
|
|
im = Image.open(io.BytesIO(buffer))
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
Note that the library rewinds the file (using ``seek(0)``) before reading the
|
|
|
|
|
image header. In addition, seek will also be used when the image data is read
|
|
|
|
|
(by the load method). If the image file is embedded in a larger file, such as a
|
|
|
|
|
tar file, you can use the :py:class:`~PIL.ContainerIO` or
|
|
|
|
|
:py:class:`~PIL.TarIO` modules to access it.
|
|
|
|
|
|
2022-04-15 15:02:52 +03:00
|
|
|
|
Reading from URL
|
|
|
|
|
^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
from PIL import Image
|
|
|
|
|
from urllib.request import urlopen
|
2024-01-01 20:06:46 +03:00
|
|
|
|
url = "https://python-pillow.org/assets/images/pillow-logo.png"
|
2022-04-15 15:02:52 +03:00
|
|
|
|
img = Image.open(urlopen(url))
|
|
|
|
|
|
|
|
|
|
|
2013-10-07 05:12:39 +04:00
|
|
|
|
Reading from a tar archive
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
2017-05-06 16:20:34 +03:00
|
|
|
|
from PIL import Image, TarIO
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2017-05-06 16:20:34 +03:00
|
|
|
|
fp = TarIO.TarIO("Tests/images/hopper.tar", "hopper.jpg")
|
2013-10-07 05:12:39 +04:00
|
|
|
|
im = Image.open(fp)
|
|
|
|
|
|
2021-12-18 13:23:07 +03:00
|
|
|
|
|
|
|
|
|
Batch processing
|
|
|
|
|
^^^^^^^^^^^^^^^^
|
|
|
|
|
|
2021-12-18 13:59:09 +03:00
|
|
|
|
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.
|
2021-12-18 13:23:07 +03:00
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
2021-12-20 00:48:23 +03:00
|
|
|
|
import glob
|
2021-12-18 13:23:07 +03:00
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
|
|
2021-12-20 00:48:23 +03:00
|
|
|
|
paths = glob.glob("*.png")
|
2021-12-18 13:59:09 +03:00
|
|
|
|
for path in paths:
|
|
|
|
|
compress_image(path, path[:-4] + ".jpg")
|
|
|
|
|
|
|
|
|
|
Since images can also be opened from a ``Path`` from the ``pathlib`` module,
|
2021-12-20 00:48:23 +03:00
|
|
|
|
the example could be modified to use ``pathlib`` instead of the ``glob``
|
|
|
|
|
module.
|
2021-12-18 13:59:09 +03:00
|
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
|
|
from pathlib import Path
|
2021-12-18 13:23:07 +03:00
|
|
|
|
|
2021-12-19 15:26:30 +03:00
|
|
|
|
paths = Path(".").glob("*.png")
|
2021-12-18 13:59:09 +03:00
|
|
|
|
for path in paths:
|
2021-12-20 01:39:09 +03:00
|
|
|
|
compress_image(path, path.stem + ".jpg")
|
2021-12-18 13:23:07 +03:00
|
|
|
|
|
|
|
|
|
|
2013-10-07 08:59:08 +04:00
|
|
|
|
Controlling the decoder
|
2013-10-07 05:12:39 +04:00
|
|
|
|
-----------------------
|
|
|
|
|
|
|
|
|
|
Some decoders allow you to manipulate the image while reading it from a file.
|
|
|
|
|
This can often be used to speed up decoding when creating thumbnails (when
|
|
|
|
|
speed is usually more important than quality) and printing to a monochrome
|
2023-10-19 11:12:01 +03:00
|
|
|
|
laser printer (when only a grayscale version of the image is needed).
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
The :py:meth:`~PIL.Image.Image.draft` method manipulates an opened but not yet
|
|
|
|
|
loaded image so it as closely as possible matches the given mode and size. This
|
|
|
|
|
is done by reconfiguring the image decoder.
|
|
|
|
|
|
|
|
|
|
Reading in draft mode
|
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
2016-09-29 13:11:19 +03:00
|
|
|
|
This is only available for JPEG and MPO files.
|
|
|
|
|
|
2013-10-07 05:12:39 +04:00
|
|
|
|
::
|
|
|
|
|
|
2016-09-29 13:11:38 +03:00
|
|
|
|
from PIL import Image
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
Improve handling of file resources
Follow Python's file object semantics. User code is responsible for
closing resources (usually through a context manager) in a deterministic
way.
To achieve this, remove __del__ functions. These functions used to
closed open file handlers in an attempt to silence Python
ResourceWarnings. However, using __del__ has the following drawbacks:
- __del__ isn't called until the object's reference count reaches 0.
Therefore, resource handlers remain open or in use longer than
necessary.
- The __del__ method isn't guaranteed to execute on system exit. See the
Python documentation:
https://docs.python.org/3/reference/datamodel.html#object.__del__
> It is not guaranteed that __del__() methods are called for objects
> that still exist when the interpreter exits.
- Exceptions that occur inside __del__ are ignored instead of raised.
This has the potential of hiding bugs. This is also in the Python
documentation:
> Warning: Due to the precarious circumstances under which __del__()
> methods are invoked, exceptions that occur during their execution
> are ignored, and a warning is printed to sys.stderr instead.
Instead, always close resource handlers when they are no longer in use.
This will close the file handler at a specified point in the user's code
and not wait until the interpreter chooses to. It is always guaranteed
to run. And, if an exception occurs while closing the file handler, the
bug will not be ignored.
Now, when code receives a ResourceWarning, it will highlight an area
that is mishandling resources. It should not simply be silenced, but
fixed by closing resources with a context manager.
All warnings that were emitted during tests have been cleaned up. To
enable warnings, I passed the `-Wa` CLI option to Python. This exposed
some mishandling of resources in ImageFile.__init__() and
SpiderImagePlugin.loadImageSeries(), they too were fixed.
2019-05-25 19:30:58 +03:00
|
|
|
|
with Image.open(file) as im:
|
|
|
|
|
print("original =", im.mode, im.size)
|
|
|
|
|
|
|
|
|
|
im.draft("L", (100, 100))
|
|
|
|
|
print("draft =", im.mode, im.size)
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
2013-10-07 09:54:39 +04:00
|
|
|
|
This prints something like::
|
2013-10-07 05:12:39 +04:00
|
|
|
|
|
|
|
|
|
original = RGB (512, 512)
|
|
|
|
|
draft = L (128, 128)
|
|
|
|
|
|
|
|
|
|
Note that the resulting image may not exactly match the requested mode and
|
|
|
|
|
size. To make sure that the image is not larger than the given size, use the
|
|
|
|
|
thumbnail method instead.
|