Merge pull request #4697 from nulano/docs-imageshow

This commit is contained in:
Hugo van Kemenade 2020-06-27 14:09:44 +03:00 committed by GitHub
commit 92561bdcdc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
29 changed files with 393 additions and 221 deletions

View File

@ -4,6 +4,14 @@ PIL Package (autodoc of remaining modules)
Reference for modules whose documentation has not yet been ported or written Reference for modules whose documentation has not yet been ported or written
can be found here. can be found here.
:mod:`PIL` Module
-----------------
.. py:module:: PIL
.. autoexception:: UnidentifiedImageError
:show-inheritance:
:mod:`BdfFontFile` Module :mod:`BdfFontFile` Module
------------------------- -------------------------
@ -52,21 +60,12 @@ can be found here.
:undoc-members: :undoc-members:
:show-inheritance: :show-inheritance:
.. intentionally skipped documenting this because it's not documented anywhere
:mod:`ImageDraw2` Module :mod:`ImageDraw2` Module
------------------------ ------------------------
.. automodule:: PIL.ImageDraw2 .. automodule:: PIL.ImageDraw2
:members: :members:
:undoc-members: :member-order: bysource
:show-inheritance:
:mod:`ImageShow` Module
-----------------------
.. automodule:: PIL.ImageShow
:members:
:undoc-members: :undoc-members:
:show-inheritance: :show-inheritance:
@ -78,14 +77,6 @@ can be found here.
:undoc-members: :undoc-members:
:show-inheritance: :show-inheritance:
:mod:`JpegPresets` Module
-------------------------
.. automodule:: PIL.JpegPresets
:members:
:undoc-members:
:show-inheritance:
:mod:`PaletteFile` Module :mod:`PaletteFile` Module
------------------------- -------------------------
@ -140,12 +131,3 @@ can be found here.
:members: :members:
:undoc-members: :undoc-members:
:show-inheritance: :show-inheritance:
:mod:`_binary` Module
---------------------
.. automodule:: PIL._binary
:members:
:undoc-members:
:show-inheritance:

View File

@ -22,7 +22,7 @@ import sphinx_rtd_theme
# -- General configuration ------------------------------------------------ # -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here. # If your documentation needs a minimal Sphinx version, state it here.
# needs_sphinx = '1.0' needs_sphinx = "2.4"
# Add any Sphinx extension module names here, as strings. They can be # Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom

View File

@ -7,7 +7,8 @@
The :py:mod:`ExifTags` module exposes two dictionaries which The :py:mod:`ExifTags` module exposes two dictionaries which
provide constants and clear-text names for various well-known EXIF tags. provide constants and clear-text names for various well-known EXIF tags.
.. py:class:: PIL.ExifTags.TAGS .. py:data:: TAGS
:type: dict
The TAG dictionary maps 16-bit integer EXIF tag enumerations to The TAG dictionary maps 16-bit integer EXIF tag enumerations to
descriptive string names. For instance: descriptive string names. For instance:
@ -16,7 +17,8 @@ provide constants and clear-text names for various well-known EXIF tags.
>>> TAGS[0x010e] >>> TAGS[0x010e]
'ImageDescription' 'ImageDescription'
.. py:class:: PIL.ExifTags.GPSTAGS .. py:data:: GPSTAGS
:type: dict
The GPSTAGS dictionary maps 8-bit integer EXIF gps enumerations to The GPSTAGS dictionary maps 8-bit integer EXIF gps enumerations to
descriptive string names. For instance: descriptive string names. For instance:

View File

@ -124,7 +124,7 @@ Example: Draw Multiline Text
Functions Functions
--------- ---------
.. py:class:: PIL.ImageDraw.Draw(im, mode=None) .. py:method:: Draw(im, mode=None)
Creates an object that can be used to draw in the given image. Creates an object that can be used to draw in the given image.
@ -140,13 +140,13 @@ Functions
Methods Methods
------- -------
.. py:method:: PIL.ImageDraw.ImageDraw.getfont() .. py:method:: ImageDraw.getfont()
Get the current default font. Get the current default font.
:returns: An image font. :returns: An image font.
.. py:method:: PIL.ImageDraw.ImageDraw.arc(xy, start, end, fill=None, width=0) .. py:method:: ImageDraw.arc(xy, start, end, fill=None, width=0)
Draws an arc (a portion of a circle outline) between the start and end Draws an arc (a portion of a circle outline) between the start and end
angles, inside the given bounding box. angles, inside the given bounding box.
@ -162,7 +162,7 @@ Methods
.. versionadded:: 5.3.0 .. versionadded:: 5.3.0
.. py:method:: PIL.ImageDraw.ImageDraw.bitmap(xy, bitmap, fill=None) .. py:method:: ImageDraw.bitmap(xy, bitmap, fill=None)
Draws a bitmap (mask) at the given position, using the current fill color Draws a bitmap (mask) at the given position, using the current fill color
for the non-zero portions. The bitmap should be a valid transparency mask for the non-zero portions. The bitmap should be a valid transparency mask
@ -173,7 +173,7 @@ Methods
To paste pixel data into an image, use the To paste pixel data into an image, use the
:py:meth:`~PIL.Image.Image.paste` method on the image itself. :py:meth:`~PIL.Image.Image.paste` method on the image itself.
.. py:method:: PIL.ImageDraw.ImageDraw.chord(xy, start, end, fill=None, outline=None, width=1) .. py:method:: ImageDraw.chord(xy, start, end, fill=None, outline=None, width=1)
Same as :py:meth:`~PIL.ImageDraw.ImageDraw.arc`, but connects the end points Same as :py:meth:`~PIL.ImageDraw.ImageDraw.arc`, but connects the end points
with a straight line. with a straight line.
@ -187,7 +187,7 @@ Methods
.. versionadded:: 5.3.0 .. versionadded:: 5.3.0
.. py:method:: PIL.ImageDraw.ImageDraw.ellipse(xy, fill=None, outline=None, width=1) .. py:method:: ImageDraw.ellipse(xy, fill=None, outline=None, width=1)
Draws an ellipse inside the given bounding box. Draws an ellipse inside the given bounding box.
@ -200,9 +200,9 @@ Methods
.. versionadded:: 5.3.0 .. versionadded:: 5.3.0
.. py:method:: PIL.ImageDraw.ImageDraw.line(xy, fill=None, width=0, joint=None) .. py:method:: ImageDraw.line(xy, fill=None, width=0, joint=None)
Draws a line between the coordinates in the **xy** list. Draws a line between the coordinates in the ``xy`` list.
:param xy: Sequence of either 2-tuples like ``[(x, y), (x, y), ...]`` or :param xy: Sequence of either 2-tuples like ``[(x, y), (x, y), ...]`` or
numeric values like ``[x, y, x, y, ...]``. numeric values like ``[x, y, x, y, ...]``.
@ -216,7 +216,7 @@ Methods
.. versionadded:: 5.3.0 .. versionadded:: 5.3.0
.. py:method:: PIL.ImageDraw.ImageDraw.pieslice(xy, start, end, fill=None, outline=None, width=1) .. py:method:: ImageDraw.pieslice(xy, start, end, fill=None, outline=None, width=1)
Same as arc, but also draws straight lines between the end points and the Same as arc, but also draws straight lines between the end points and the
center of the bounding box. center of the bounding box.
@ -233,7 +233,7 @@ Methods
.. versionadded:: 5.3.0 .. versionadded:: 5.3.0
.. py:method:: PIL.ImageDraw.ImageDraw.point(xy, fill=None) .. py:method:: ImageDraw.point(xy, fill=None)
Draws points (individual pixels) at the given coordinates. Draws points (individual pixels) at the given coordinates.
@ -241,7 +241,7 @@ Methods
numeric values like ``[x, y, x, y, ...]``. numeric values like ``[x, y, x, y, ...]``.
:param fill: Color to use for the point. :param fill: Color to use for the point.
.. py:method:: PIL.ImageDraw.ImageDraw.polygon(xy, fill=None, outline=None) .. py:method:: ImageDraw.polygon(xy, fill=None, outline=None)
Draws a polygon. Draws a polygon.
@ -254,7 +254,7 @@ Methods
:param outline: Color to use for the outline. :param outline: Color to use for the outline.
:param fill: Color to use for the fill. :param fill: Color to use for the fill.
.. py:method:: PIL.ImageDraw.ImageDraw.rectangle(xy, fill=None, outline=None, width=1) .. py:method:: ImageDraw.rectangle(xy, fill=None, outline=None, width=1)
Draws a rectangle. Draws a rectangle.
@ -267,13 +267,13 @@ Methods
.. versionadded:: 5.3.0 .. versionadded:: 5.3.0
.. py:method:: PIL.ImageDraw.ImageDraw.shape(shape, fill=None, outline=None) .. py:method:: ImageDraw.shape(shape, fill=None, outline=None)
.. warning:: This method is experimental. .. warning:: This method is experimental.
Draw a shape. Draw a shape.
.. py:method:: PIL.ImageDraw.ImageDraw.text(xy, text, fill=None, font=None, anchor=None, spacing=4, align="left", direction=None, features=None, language=None, stroke_width=0, stroke_fill=None) .. py:method:: ImageDraw.text(xy, text, fill=None, font=None, anchor=None, spacing=4, align="left", direction=None, features=None, language=None, stroke_width=0, stroke_fill=None)
Draws the string at the given position. Draws the string at the given position.
@ -325,7 +325,7 @@ Methods
.. versionadded:: 6.2.0 .. versionadded:: 6.2.0
.. py:method:: PIL.ImageDraw.ImageDraw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=4, align="left", direction=None, features=None, language=None) .. py:method:: ImageDraw.multiline_text(xy, text, fill=None, font=None, anchor=None, spacing=4, align="left", direction=None, features=None, language=None)
Draws the string at the given position. Draws the string at the given position.
@ -362,7 +362,7 @@ Methods
.. versionadded:: 6.0.0 .. versionadded:: 6.0.0
.. py:method:: PIL.ImageDraw.ImageDraw.textsize(text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0) .. py:method:: ImageDraw.textsize(text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0)
Return the size of the given string, in pixels. Return the size of the given string, in pixels.
@ -401,7 +401,7 @@ Methods
.. versionadded:: 6.2.0 .. versionadded:: 6.2.0
.. py:method:: PIL.ImageDraw.ImageDraw.multiline_textsize(text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0) .. py:method:: ImageDraw.multiline_textsize(text, font=None, spacing=4, direction=None, features=None, language=None, stroke_width=0)
Return the size of the given string, in pixels. Return the size of the given string, in pixels.
@ -439,7 +439,7 @@ Methods
.. versionadded:: 6.2.0 .. versionadded:: 6.2.0
.. py:method:: PIL.ImageDraw.getdraw(im=None, hints=None) .. py:method:: getdraw(im=None, hints=None)
.. warning:: This method is experimental. .. warning:: This method is experimental.
@ -450,7 +450,7 @@ Methods
:param hints: An optional list of hints. :param hints: An optional list of hints.
:returns: A (drawing context, drawing resource factory) tuple. :returns: A (drawing context, drawing resource factory) tuple.
.. py:method:: PIL.ImageDraw.floodfill(image, xy, value, border=None, thresh=0) .. py:method:: floodfill(image, xy, value, border=None, thresh=0)
.. warning:: This method is experimental. .. warning:: This method is experimental.

View File

@ -29,7 +29,8 @@ Classes
All enhancement classes implement a common interface, containing a single All enhancement classes implement a common interface, containing a single
method: method:
.. py:class:: PIL.ImageEnhance._Enhance .. py:class:: _Enhance
.. py:method:: enhance(factor) .. py:method:: enhance(factor)
Returns an enhanced image. Returns an enhanced image.
@ -40,7 +41,7 @@ method:
etc), and higher values more. There are no restrictions etc), and higher values more. There are no restrictions
on this value. on this value.
.. py:class:: PIL.ImageEnhance.Color(image) .. py:class:: Color(image)
Adjust image color balance. Adjust image color balance.
@ -49,7 +50,7 @@ method:
factor of 0.0 gives a black and white image. A factor of 1.0 gives factor of 0.0 gives a black and white image. A factor of 1.0 gives
the original image. the original image.
.. py:class:: PIL.ImageEnhance.Contrast(image) .. py:class:: Contrast(image)
Adjust image contrast. Adjust image contrast.
@ -57,7 +58,7 @@ method:
to the contrast control on a TV set. An enhancement factor of 0.0 to the contrast control on a TV set. An enhancement factor of 0.0
gives a solid grey image. A factor of 1.0 gives the original image. gives a solid grey image. A factor of 1.0 gives the original image.
.. py:class:: PIL.ImageEnhance.Brightness(image) .. py:class:: Brightness(image)
Adjust image brightness. Adjust image brightness.
@ -65,7 +66,7 @@ method:
enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the enhancement factor of 0.0 gives a black image. A factor of 1.0 gives the
original image. original image.
.. py:class:: PIL.ImageEnhance.Sharpness(image) .. py:class:: Sharpness(image)
Adjust image sharpness. Adjust image sharpness.

View File

@ -0,0 +1,27 @@
.. py:module:: PIL.ImageShow
.. py:currentmodule:: PIL.ImageShow
:py:mod:`ImageShow` Module
==========================
The :py:mod:`ImageShow` Module is used to display images.
All default viewers convert the image to be shown to PNG format.
.. autofunction:: PIL.ImageShow.show
.. autoclass:: WindowsViewer
.. autoclass:: MacViewer
.. class:: UnixViewer
The following viewers may be registered on Unix-based systems, if the given command is found:
.. autoclass:: PIL.ImageShow.DisplayViewer
.. autoclass:: PIL.ImageShow.EogViewer
.. autoclass:: PIL.ImageShow.XVViewer
.. autofunction:: PIL.ImageShow.register
.. autoclass:: PIL.ImageShow.Viewer
:member-order: bysource
:members:
:undoc-members:

View File

@ -7,7 +7,7 @@
The :py:mod:`ImageStat` module calculates global statistics for an image, or The :py:mod:`ImageStat` module calculates global statistics for an image, or
for a region of an image. for a region of an image.
.. py:class:: PIL.ImageStat.Stat(image_or_list, mask=None) .. py:class:: Stat(image_or_list, mask=None)
Calculate statistics for the given image. If a mask is included, Calculate statistics for the given image. If a mask is included,
only the regions covered by that mask are included in the only the regions covered by that mask are included in the
@ -22,13 +22,13 @@ for a region of an image.
.. note:: .. note::
This relies on the :py:meth:`~PIL.Image.histogram` method, and This relies on the :py:meth:`~PIL.Image.Image.histogram` method, and
simply returns the low and high bins used. This is correct for simply returns the low and high bins used. This is correct for
images with 8 bits per channel, but fails for other modes such as images with 8 bits per channel, but fails for other modes such as
``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.getextrema` to ``I`` or ``F``. Instead, use :py:meth:`~PIL.Image.Image.getextrema` to
return per-band extrema for the image. This is more correct and return per-band extrema for the image. This is more correct and
efficient because, for non-8-bit modes, the histogram method uses efficient because, for non-8-bit modes, the histogram method uses
:py:meth:`~PIL.Image.getextrema` to determine the bins used. :py:meth:`~PIL.Image.Image.getextrema` to determine the bins used.
.. py:attribute:: count .. py:attribute:: count

View File

@ -0,0 +1,11 @@
.. py:currentmodule:: PIL.JpegPresets
:py:mod:`JpegPresets` Module
============================
.. automodule:: PIL.JpegPresets
.. data:: presets
:type: dict
A dictionary of all supported presets.

View File

@ -10,8 +10,8 @@ metadata tag numbers, names, and type information.
.. method:: lookup(tag) .. method:: lookup(tag)
:param tag: Integer tag number :param tag: Integer tag number
:returns: Taginfo namedtuple, From the ``TAGS_V2`` info if possible, :returns: Taginfo namedtuple, From the :py:data:`~PIL.TiffTags.TAGS_V2` info if possible,
otherwise just populating the value and name from ``TAGS``. otherwise just populating the value and name from :py:data:`~PIL.TiffTags.TAGS`.
If the tag is not recognized, "unknown" is returned for the name If the tag is not recognized, "unknown" is returned for the name
.. versionadded:: 3.1.0 .. versionadded:: 3.1.0
@ -22,7 +22,7 @@ metadata tag numbers, names, and type information.
:param value: Integer Tag Number :param value: Integer Tag Number
:param name: Tag Name :param name: Tag Name
:param type: Integer type from :py:attr:`PIL.TiffTags.TYPES` :param type: Integer type from :py:data:`PIL.TiffTags.TYPES`
:param length: Array length: 0 == variable, 1 == single value, n = fixed :param length: Array length: 0 == variable, 1 == single value, n = fixed
:param enum: Dict of name:integer value options for an enumeration :param enum: Dict of name:integer value options for an enumeration
@ -33,15 +33,17 @@ metadata tag numbers, names, and type information.
.. versionadded:: 3.0.0 .. versionadded:: 3.0.0
.. py:attribute:: PIL.TiffTags.TAGS_V2 .. py:data:: PIL.TiffTags.TAGS_V2
:type: dict
The ``TAGS_V2`` dictionary maps 16-bit integer tag numbers to The ``TAGS_V2`` dictionary maps 16-bit integer tag numbers to
:py:class:`PIL.TagTypes.TagInfo` tuples for metadata fields defined in the TIFF :py:class:`PIL.TiffTags.TagInfo` tuples for metadata fields defined in the TIFF
spec. spec.
.. versionadded:: 3.0.0 .. versionadded:: 3.0.0
.. py:attribute:: PIL.TiffTags.TAGS .. py:data:: PIL.TiffTags.TAGS
:type: dict
The ``TAGS`` dictionary maps 16-bit integer TIFF tag number to The ``TAGS`` dictionary maps 16-bit integer TIFF tag number to
descriptive string names. For instance: descriptive string names. For instance:
@ -50,10 +52,11 @@ metadata tag numbers, names, and type information.
>>> TAGS[0x010e] >>> TAGS[0x010e]
'ImageDescription' 'ImageDescription'
This dictionary contains a superset of the tags in TAGS_V2, common This dictionary contains a superset of the tags in :py:data:`~PIL.TiffTags.TAGS_V2`, common
EXIF tags, and other well known metadata tags. EXIF tags, and other well known metadata tags.
.. py:attribute:: PIL.TiffTags.TYPES .. py:data:: PIL.TiffTags.TYPES
:type: dict
The ``TYPES`` dictionary maps the TIFF type short integer to a The ``TYPES`` dictionary maps the TIFF type short integer to a
human readable type name. human readable type name.

View File

@ -7,8 +7,8 @@ Reference
Image Image
ImageChops ImageChops
ImageColor
ImageCms ImageCms
ImageColor
ImageDraw ImageDraw
ImageEnhance ImageEnhance
ImageFile ImageFile
@ -22,11 +22,13 @@ Reference
ImagePath ImagePath
ImageQt ImageQt
ImageSequence ImageSequence
ImageShow
ImageStat ImageStat
ImageTk ImageTk
ImageWin ImageWin
ExifTags ExifTags
TiffTags TiffTags
JpegPresets
PSDraw PSDraw
PixelAccess PixelAccess
PyAccess PyAccess

View File

@ -7,4 +7,4 @@ Internal Reference Docs
open_files open_files
limits limits
block_allocator block_allocator
internal_modules

View File

@ -0,0 +1,38 @@
Internal Modules
================
:mod:`_binary` Module
---------------------
.. automodule:: PIL._binary
:members:
:undoc-members:
:show-inheritance:
:mod:`_tkinter_finder` Module
-----------------------------
.. automodule:: PIL._tkinter_finder
:members:
:undoc-members:
:show-inheritance:
:mod:`_util` Module
-------------------
.. automodule:: PIL._util
:members:
:undoc-members:
:show-inheritance:
:mod:`_version` Module
----------------------
.. module:: PIL._version
.. data:: __version__
:annotation:
:type: str
This is the master version number for Pillow,
all other uses reference this module.

View File

@ -9,4 +9,5 @@ pyflakes
pyroma pyroma
pytest pytest
pytest-cov pytest-cov
sphinx>=2.4
sphinx-rtd-theme sphinx-rtd-theme

View File

@ -17,13 +17,13 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
"""
Parse X Bitmap Distribution Format (BDF)
"""
from . import FontFile, Image from . import FontFile, Image
# --------------------------------------------------------------------
# parse X Bitmap Distribution Format (BDF)
# --------------------------------------------------------------------
bdf_slant = { bdf_slant = {
"R": "Roman", "R": "Roman",
"I": "Italic", "I": "Italic",
@ -78,11 +78,9 @@ def bdf_char(f):
return id, int(props["ENCODING"]), bbox, im return id, int(props["ENCODING"]), bbox, im
##
# Font file plugin for the X11 BDF format.
class BdfFontFile(FontFile.FontFile): class BdfFontFile(FontFile.FontFile):
"""Font file plugin for the X11 BDF format."""
def __init__(self, fp): def __init__(self, fp):
super().__init__() super().__init__()

View File

@ -14,14 +14,16 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
##
# A file object that provides read access to a part of an existing
# file (for example a TAR file).
import io import io
class ContainerIO: class ContainerIO:
"""
A file object that provides read access to a part of an existing
file (for example a TAR file).
"""
def __init__(self, file, offset, length): def __init__(self, file, offset, length):
""" """
Create file object. Create file object.

View File

@ -9,13 +9,11 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
## """
# This module provides constants and clear-text names for various This module provides constants and clear-text names for various
# well-known EXIF tags. well-known EXIF tags.
## """
##
# Maps EXIF tags to tag names.
TAGS = { TAGS = {
# possibly incomplete # possibly incomplete
@ -280,9 +278,8 @@ TAGS = {
0xC74E: "OpcodeList3", 0xC74E: "OpcodeList3",
0xC761: "NoiseProfile", 0xC761: "NoiseProfile",
} }
"""Maps EXIF tags to tag names."""
##
# Maps EXIF GPS tags to tag names.
GPSTAGS = { GPSTAGS = {
0: "GPSVersionID", 0: "GPSVersionID",
@ -318,3 +315,4 @@ GPSTAGS = {
30: "GPSDifferential", 30: "GPSDifferential",
31: "GPSHPositioningError", 31: "GPSHPositioningError",
} }
"""Maps EXIF GPS tags to tag names."""

View File

@ -23,18 +23,15 @@ WIDTH = 800
def puti16(fp, values): def puti16(fp, values):
# write network order (big-endian) 16-bit sequence """Write network order (big-endian) 16-bit sequence"""
for v in values: for v in values:
if v < 0: if v < 0:
v += 65536 v += 65536
fp.write(_binary.o16be(v)) fp.write(_binary.o16be(v))
##
# Base class for raster font file handlers.
class FontFile: class FontFile:
"""Base class for raster font file handlers."""
bitmap = None bitmap = None

View File

@ -14,26 +14,30 @@
# #
# NOTE: This format cannot be automatically recognized, so the """
# class is not registered for use with Image.open(). To open a .. note::
# gd file, use the GdImageFile.open() function instead. This format cannot be automatically recognized, so the
class is not registered for use with :py:func:`PIL.Image.open()`. To open a
gd file, use the :py:func:`PIL.GdImageFile.open()` function instead.
# THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This .. warning::
# implementation is provided for convenience and demonstrational THE GD FORMAT IS NOT DESIGNED FOR DATA INTERCHANGE. This
# purposes only. implementation is provided for convenience and demonstrational
purposes only.
"""
from . import ImageFile, ImagePalette, UnidentifiedImageError from . import ImageFile, ImagePalette, UnidentifiedImageError
from ._binary import i8, i16be as i16, i32be as i32 from ._binary import i8, i16be as i16, i32be as i32
##
# Image plugin for the GD uncompressed format. Note that this format
# is not supported by the standard <b>Image.open</b> function. To use
# this plugin, you have to import the <b>GdImageFile</b> module and
# use the <b>GdImageFile.open</b> function.
class GdImageFile(ImageFile.ImageFile): class GdImageFile(ImageFile.ImageFile):
"""
Image plugin for the GD uncompressed format. Note that this format
is not supported by the standard :py:func:`PIL.Image.open()` function. To use
this plugin, you have to import the :py:mod:`PIL.GdImageFile` module and
use the :py:func:`PIL.GdImageFile.open()` function.
"""
format = "GD" format = "GD"
format_description = "GD uncompressed images" format_description = "GD uncompressed images"

View File

@ -13,17 +13,19 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
"""
Stuff to translate curve segments to palette values (derived from
the corresponding code in GIMP, written by Federico Mena Quintero.
See the GIMP distribution for more information.)
"""
from math import log, pi, sin, sqrt from math import log, pi, sin, sqrt
from ._binary import o8 from ._binary import o8
# --------------------------------------------------------------------
# Stuff to translate curve segments to palette values (derived from
# the corresponding code in GIMP, written by Federico Mena Quintero.
# See the GIMP distribution for more information.)
#
EPSILON = 1e-10 EPSILON = 1e-10
"""""" # Enable auto-doc for data member
def linear(middle, pos): def linear(middle, pos):
@ -58,6 +60,7 @@ def sphere_decreasing(middle, pos):
SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing] SEGMENTS = [linear, curved, sine, sphere_increasing, sphere_decreasing]
"""""" # Enable auto-doc for data member
class GradientFile: class GradientFile:
@ -98,11 +101,9 @@ class GradientFile:
return b"".join(palette), "RGBA" return b"".join(palette), "RGBA"
##
# File handler for GIMP's gradient format.
class GimpGradientFile(GradientFile): class GimpGradientFile(GradientFile):
"""File handler for GIMP's gradient format."""
def __init__(self, fp): def __init__(self, fp):
if fp.readline()[:13] != b"GIMP Gradient": if fp.readline()[:13] != b"GIMP Gradient":

View File

@ -18,11 +18,9 @@ import re
from ._binary import o8 from ._binary import o8
##
# File handler for GIMP's palette format.
class GimpPaletteFile: class GimpPaletteFile:
"""File handler for GIMP's palette format."""
rawmode = "RGB" rawmode = "RGB"

View File

@ -16,21 +16,35 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
"""
(Experimental) WCK-style drawing interface operations
.. seealso:: :py:mod:`PIL.ImageDraw`
"""
from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath from . import Image, ImageColor, ImageDraw, ImageFont, ImagePath
class Pen: class Pen:
"""Stores an outline color and width."""
def __init__(self, color, width=1, opacity=255): def __init__(self, color, width=1, opacity=255):
self.color = ImageColor.getrgb(color) self.color = ImageColor.getrgb(color)
self.width = width self.width = width
class Brush: class Brush:
"""Stores a fill color"""
def __init__(self, color, opacity=255): def __init__(self, color, opacity=255):
self.color = ImageColor.getrgb(color) self.color = ImageColor.getrgb(color)
class Font: class Font:
"""Stores a TrueType font and color"""
def __init__(self, color, file, size=12): def __init__(self, color, file, size=12):
# FIXME: add support for bitmap fonts # FIXME: add support for bitmap fonts
self.color = ImageColor.getrgb(color) self.color = ImageColor.getrgb(color)
@ -38,6 +52,10 @@ class Font:
class Draw: class Draw:
"""
(Experimental) WCK-style drawing interface
"""
def __init__(self, image, size=None, color=None): def __init__(self, image, size=None, color=None):
if not hasattr(image, "im"): if not hasattr(image, "im"):
image = Image.new(image, size, color) image = Image.new(image, size, color)
@ -73,35 +91,89 @@ class Draw:
getattr(self.draw, op)(xy, fill=fill, outline=outline) getattr(self.draw, op)(xy, fill=fill, outline=outline)
def settransform(self, offset): def settransform(self, offset):
"""Sets a transformation offset."""
(xoffset, yoffset) = offset (xoffset, yoffset) = offset
self.transform = (1, 0, xoffset, 0, 1, yoffset) self.transform = (1, 0, xoffset, 0, 1, yoffset)
def arc(self, xy, start, end, *options): def arc(self, xy, start, end, *options):
"""
Draws an arc (a portion of a circle outline) between the start and end
angles, inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.arc`
"""
self.render("arc", xy, start, end, *options) self.render("arc", xy, start, end, *options)
def chord(self, xy, start, end, *options): def chord(self, xy, start, end, *options):
"""
Same as :py:meth:`~PIL.ImageDraw2.ImageDraw.arc`, but connects the end points
with a straight line.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.chord`
"""
self.render("chord", xy, start, end, *options) self.render("chord", xy, start, end, *options)
def ellipse(self, xy, *options): def ellipse(self, xy, *options):
"""
Draws an ellipse inside the given bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.ellipse`
"""
self.render("ellipse", xy, *options) self.render("ellipse", xy, *options)
def line(self, xy, *options): def line(self, xy, *options):
"""
Draws a line between the coordinates in the ``xy`` list.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.line`
"""
self.render("line", xy, *options) self.render("line", xy, *options)
def pieslice(self, xy, start, end, *options): def pieslice(self, xy, start, end, *options):
"""
Same as arc, but also draws straight lines between the end points and the
center of the bounding box.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.pieslice`
"""
self.render("pieslice", xy, start, end, *options) self.render("pieslice", xy, start, end, *options)
def polygon(self, xy, *options): def polygon(self, xy, *options):
"""
Draws a polygon.
The polygon outline consists of straight lines between the given
coordinates, plus a straight line between the last and the first
coordinate.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.polygon`
"""
self.render("polygon", xy, *options) self.render("polygon", xy, *options)
def rectangle(self, xy, *options): def rectangle(self, xy, *options):
"""
Draws a rectangle.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.rectangle`
"""
self.render("rectangle", xy, *options) self.render("rectangle", xy, *options)
def text(self, xy, text, font): def text(self, xy, text, font):
"""
Draws the string at the given position.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.text`
"""
if self.transform: if self.transform:
xy = ImagePath.Path(xy) xy = ImagePath.Path(xy)
xy.transform(self.transform) xy.transform(self.transform)
self.draw.text(xy, text, font=font.font, fill=font.color) self.draw.text(xy, text, font=font.font, fill=font.color)
def textsize(self, text, font): def textsize(self, text, font):
"""
Return the size of the given string, in pixels.
.. seealso:: :py:meth:`PIL.ImageDraw.ImageDraw.textsize`
"""
return self.draw.textsize(text, font=font.font) return self.draw.textsize(text, font=font.font)

View File

@ -24,6 +24,14 @@ _viewers = []
def register(viewer, order=1): def register(viewer, order=1):
"""
The :py:func:`register` function is used to register additional viewers.
:param viewer: The viewer to be registered.
:param order:
Zero or a negative integer to prepend this viewer to the list,
a positive integer to append it.
"""
try: try:
if issubclass(viewer, Viewer): if issubclass(viewer, Viewer):
viewer = viewer() viewer = viewer()
@ -40,9 +48,9 @@ def show(image, title=None, **options):
Display a given image. Display a given image.
:param image: An image object. :param image: An image object.
:param title: Optional title. Not all viewers can display the title. :param title: Optional title. Not all viewers can display the title.
:param \**options: Additional viewer options. :param \**options: Additional viewer options.
:returns: True if a suitable viewer was found, false otherwise. :returns: ``True`` if a suitable viewer was found, ``False`` otherwise.
""" """
for viewer in _viewers: for viewer in _viewers:
if viewer.show(image, title=title, **options): if viewer.show(image, title=title, **options):
@ -56,6 +64,10 @@ class Viewer:
# main api # main api
def show(self, image, **options): def show(self, image, **options):
"""
The main function for displaying an image.
Converts the given image to the target format and displays it.
"""
# save temporary image to disk # save temporary image to disk
if not ( if not (
@ -70,25 +82,31 @@ class Viewer:
# hook methods # hook methods
format = None format = None
"""The format to convert the image into."""
options = {} options = {}
"""Additional options used to convert the image."""
def get_format(self, image): def get_format(self, image):
"""Return format name, or None to save as PGM/PPM""" """Return format name, or ``None`` to save as PGM/PPM."""
return self.format return self.format
def get_command(self, file, **options): def get_command(self, file, **options):
"""
Returns the command used to display the file.
Not implemented in the base class.
"""
raise NotImplementedError raise NotImplementedError
def save_image(self, image): def save_image(self, image):
"""Save to temporary file, and return filename""" """Save to temporary file and return filename."""
return image._dump(format=self.get_format(image), **self.options) return image._dump(format=self.get_format(image), **self.options)
def show_image(self, image, **options): def show_image(self, image, **options):
"""Display given image""" """Display the given image."""
return self.show_file(self.save_image(image), **options) return self.show_file(self.save_image(image), **options)
def show_file(self, file, **options): def show_file(self, file, **options):
"""Display given file""" """Display the given file."""
os.system(self.get_command(file, **options)) os.system(self.get_command(file, **options))
return 1 return 1
@ -96,104 +114,116 @@ class Viewer:
# -------------------------------------------------------------------- # --------------------------------------------------------------------
class WindowsViewer(Viewer):
"""The default viewer on Windows is the default system application for PNG files."""
format = "PNG"
options = {"compress_level": 1}
def get_command(self, file, **options):
return (
'start "Pillow" /WAIT "%s" '
"&& ping -n 2 127.0.0.1 >NUL "
'&& del /f "%s"' % (file, file)
)
if sys.platform == "win32": if sys.platform == "win32":
class WindowsViewer(Viewer):
format = "PNG"
options = {"compress_level": 1}
def get_command(self, file, **options):
return (
'start "Pillow" /WAIT "%s" '
"&& ping -n 2 127.0.0.1 >NUL "
'&& del /f "%s"' % (file, file)
)
register(WindowsViewer) register(WindowsViewer)
elif sys.platform == "darwin":
class MacViewer(Viewer): class MacViewer(Viewer):
format = "PNG" """The default viewer on MacOS using ``Preview.app``."""
options = {"compress_level": 1}
def get_command(self, file, **options): format = "PNG"
# on darwin open returns immediately resulting in the temp options = {"compress_level": 1}
# file removal while app is opening
command = "open -a Preview.app" def get_command(self, file, **options):
command = "({} {}; sleep 20; rm -f {})&".format( # on darwin open returns immediately resulting in the temp
command, quote(file), quote(file) # file removal while app is opening
command = "open -a Preview.app"
command = "({} {}; sleep 20; rm -f {})&".format(
command, quote(file), quote(file)
)
return command
def show_file(self, file, **options):
"""Display given file"""
fd, path = tempfile.mkstemp()
with os.fdopen(fd, "w") as f:
f.write(file)
with open(path, "r") as f:
subprocess.Popen(
["im=$(cat); open -a Preview.app $im; sleep 20; rm -f $im"],
shell=True,
stdin=f,
) )
return command os.remove(path)
return 1
def show_file(self, file, **options):
"""Display given file"""
fd, path = tempfile.mkstemp()
with os.fdopen(fd, "w") as f:
f.write(file)
with open(path, "r") as f:
subprocess.Popen(
["im=$(cat); open -a Preview.app $im; sleep 20; rm -f $im"],
shell=True,
stdin=f,
)
os.remove(path)
return 1
if sys.platform == "darwin":
register(MacViewer) register(MacViewer)
else:
# unixoids class UnixViewer(Viewer):
format = "PNG"
options = {"compress_level": 1}
class UnixViewer(Viewer): def get_command(self, file, **options):
format = "PNG" command = self.get_command_ex(file, **options)[0]
options = {"compress_level": 1} return "({} {}; rm -f {})&".format(command, quote(file), quote(file))
def get_command(self, file, **options): def show_file(self, file, **options):
"""Display given file"""
fd, path = tempfile.mkstemp()
with os.fdopen(fd, "w") as f:
f.write(file)
with open(path, "r") as f:
command = self.get_command_ex(file, **options)[0] command = self.get_command_ex(file, **options)[0]
return "({} {}; rm -f {})&".format(command, quote(file), quote(file)) subprocess.Popen(
["im=$(cat);" + command + " $im; rm -f $im"], shell=True, stdin=f
)
os.remove(path)
return 1
def show_file(self, file, **options):
"""Display given file"""
fd, path = tempfile.mkstemp()
with os.fdopen(fd, "w") as f:
f.write(file)
with open(path, "r") as f:
command = self.get_command_ex(file, **options)[0]
subprocess.Popen(
["im=$(cat);" + command + " $im; rm -f $im"], shell=True, stdin=f
)
os.remove(path)
return 1
# implementations class DisplayViewer(UnixViewer):
"""The ImageMagick ``display`` command."""
class DisplayViewer(UnixViewer): def get_command_ex(self, file, **options):
def get_command_ex(self, file, **options): command = executable = "display"
command = executable = "display" return command, executable
return command, executable
class EogViewer(UnixViewer):
"""The GNOME Image Viewer ``eog`` command."""
def get_command_ex(self, file, **options):
command = executable = "eog"
return command, executable
class XVViewer(UnixViewer):
"""
The X Viewer ``xv`` command.
This viewer supports the ``title`` parameter.
"""
def get_command_ex(self, file, title=None, **options):
# note: xv is pretty outdated. most modern systems have
# imagemagick's display command instead.
command = executable = "xv"
if title:
command += " -name %s" % quote(title)
return command, executable
if sys.platform not in ("win32", "darwin"): # unixoids
if shutil.which("display"): if shutil.which("display"):
register(DisplayViewer) register(DisplayViewer)
class EogViewer(UnixViewer):
def get_command_ex(self, file, **options):
command = executable = "eog"
return command, executable
if shutil.which("eog"): if shutil.which("eog"):
register(EogViewer) register(EogViewer)
class XVViewer(UnixViewer):
def get_command_ex(self, file, title=None, **options):
# note: xv is pretty outdated. most modern systems have
# imagemagick's display command instead.
command = executable = "xv"
if title:
command += " -name %s" % quote(title)
return command, executable
if shutil.which("xv"): if shutil.which("xv"):
register(XVViewer) register(XVViewer)

View File

@ -1,9 +1,11 @@
""" """
JPEG quality settings equivalent to the Photoshop settings. JPEG quality settings equivalent to the Photoshop settings.
Can be used when saving JPEG files.
More presets can be added to the presets dict if needed. The following presets are available by default:
``web_low``, ``web_medium``, ``web_high``, ``web_very_high``, ``web_maximum``,
Can be use when saving JPEG file. ``low``, ``medium``, ``high``, ``maximum``.
More presets can be added to the :py:data:`presets` dict if needed.
To apply the preset, specify:: To apply the preset, specify::
@ -21,7 +23,6 @@ Example::
im.save("image_name.jpg", quality="web_high") im.save("image_name.jpg", quality="web_high")
Subsampling Subsampling
----------- -----------

View File

@ -15,11 +15,9 @@
from ._binary import o8 from ._binary import o8
##
# File handler for Teragon-style palette files.
class PaletteFile: class PaletteFile:
"""File handler for Teragon-style palette files."""
rawmode = "RGB" rawmode = "RGB"

View File

@ -48,11 +48,8 @@ def sz(s, o):
return s[o : s.index(b"\0", o)] return s[o : s.index(b"\0", o)]
##
# Font file plugin for the X11 PCF format.
class PcfFontFile(FontFile.FontFile): class PcfFontFile(FontFile.FontFile):
"""Font file plugin for the X11 PCF format."""
name = "name" name = "name"

View File

@ -18,12 +18,10 @@ import io
from . import ContainerIO from . import ContainerIO
##
# A file object that provides read access to a given member of a TAR
# file.
class TarIO(ContainerIO.ContainerIO): class TarIO(ContainerIO.ContainerIO):
"""A file object that provides read access to a given member of a TAR file."""
def __init__(self, tarfile, file): def __init__(self, tarfile, file):
""" """
Create file object. Create file object.

View File

@ -12,13 +12,16 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
# NOTE: This format cannot be automatically recognized, so the reader """
# is not registered for use with Image.open(). To open a WAL file, use This reader is based on the specification available from:
# the WalImageFile.open() function instead. https://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml
and has been tested with a few sample files found using google.
# This reader is based on the specification available from: .. note::
# https://www.flipcode.com/archives/Quake_2_BSP_File_Format.shtml This format cannot be automatically recognized, so the reader
# and has been tested with a few sample files found using google. is not registered for use with :py:func:`PIL.Image.open()`.
To open a WAL file, use the :py:func:`PIL.WalImageFile.open()` function instead.
"""
import builtins import builtins
@ -31,7 +34,7 @@ def open(filename):
Load texture from a Quake2 WAL texture file. Load texture from a Quake2 WAL texture file.
By default, a Quake2 standard palette is attached to the texture. By default, a Quake2 standard palette is attached to the texture.
To override the palette, use the <b>putpalette</b> method. To override the palette, use the :py:func:`PIL.Image.Image.putpalette()` method.
:param filename: WAL file name, or an opened file handle. :param filename: WAL file name, or an opened file handle.
:returns: An image instance. :returns: An image instance.

View File

@ -132,4 +132,8 @@ _plugins = [
class UnidentifiedImageError(OSError): class UnidentifiedImageError(OSError):
"""
Raised in :py:meth:`PIL.Image.open` if an image cannot be opened and identified.
"""
pass pass

View File

@ -11,6 +11,10 @@
# See the README file for information on usage and redistribution. # See the README file for information on usage and redistribution.
# #
"""Binary input/output support routines."""
from struct import pack, unpack_from from struct import pack, unpack_from