diff --git a/CHANGES.rst b/CHANGES.rst index 5a3432b3f..1f10204e4 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,6 +1,15 @@ Changelog (Pillow) ================== +2.3.0 (2014-01-01) +------------------ + +- Port PIL Handbook tutorial and appendices [irksep] + +- Alpha Premultiplication support for transform and resize [wiredfool] + +- Fixes to make Pypy 2.1.0 work on Ubuntu 12.04/64 [wiredfool] + 2.2.1 (2013-10-02) ------------------ diff --git a/PIL/Image.py b/PIL/Image.py index 56a4b7093..58b85d5d2 100644 --- a/PIL/Image.py +++ b/PIL/Image.py @@ -1309,6 +1309,9 @@ class Image: if self.mode in ("1", "P"): resample = NEAREST + if self.mode == 'RGBA': + return self.convert('RGBa').resize(size, resample).convert('RGBA') + if resample == ANTIALIAS: # requires stretch support (imToolkit & PIL 1.1.3) try: @@ -1606,6 +1609,9 @@ class Image: :returns: An Image object. """ + if self.mode == 'RGBA': + return self.convert('RGBa').transform(size, method, data, resample, fill).convert('RGBA') + if isinstance(method, ImageTransformHandler): return method.transform(size, self, resample=resample, fill=fill) if hasattr(method, "getdata"): @@ -1613,6 +1619,7 @@ class Image: method, data = method.getdata() if data is None: raise ValueError("missing method data") + im = new(self.mode, size, None) if method == MESH: # list of quads @@ -1620,7 +1627,7 @@ class Image: im.__transformer(box, self, QUAD, quad, resample, fill) else: im.__transformer((0, 0)+size, self, method, data, resample, fill) - + return im def __transformer(self, box, image, method, data, diff --git a/PIL/ImageFile.py b/PIL/ImageFile.py index f5e2a839f..c86f0a177 100644 --- a/PIL/ImageFile.py +++ b/PIL/ImageFile.py @@ -29,7 +29,7 @@ from PIL import Image from PIL._util import isPath -import traceback, os +import traceback, os, sys import io MAXBLOCK = 65536 @@ -136,7 +136,8 @@ class ImageFile(Image.Image): readonly = 0 - if self.filename and len(self.tile) == 1: + if self.filename and len(self.tile) == 1 and not hasattr(sys, 'pypy_version_info'): + # As of pypy 2.1.0, memory mapping was failing here. # try memory mapping d, e, o, a = self.tile[0] if d == "raw" and a[0] == self.mode and a[0] in Image._MAPMODES: diff --git a/README.rst b/README.rst index f39214e63..5917d6a21 100644 --- a/README.rst +++ b/README.rst @@ -8,6 +8,14 @@ Pillow is the "friendly" PIL fork by Alex Clark and Contributors. PIL is the Pyt .. image:: https://travis-ci.org/python-imaging/Pillow.png :target: https://travis-ci.org/python-imaging/Pillow +.. image:: https://pypip.in/v/Pillow/badge.png + :target: https://pypi.python.org/pypi/Pillow/ + :alt: Latest PyPI version + +.. image:: https://pypip.in/d/Pillow/badge.png + :target: https://pypi.python.org/pypi/Pillow/ + :alt: Number of PyPI downloads + Introduction ------------ @@ -147,6 +155,17 @@ Prerequisites are installed with on **Ubuntu 12.04 LTS** or **Raspian Wheezy 7.0 $ sudo apt-get install libtiff4-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms1-dev libwebp-dev tcl8.5-dev tk8.5-dev +Distributions +^^^^^^^^^^^^^ + +.. Note:: XXX Provide links + +Additionally, many Linux distributions now include Pillow (instead of PIL) with their distribution: + +- Fedora +- Debian/Ubuntu +- ArchLinux + Mac OS X ++++++++ @@ -197,13 +216,13 @@ Current platform support for Pillow. Binary distributions are contributed for ea +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ | Mac OS X 10.8 Mountain Lion |Yes | 2.6,2.7,3.2,3.3 | |x86-64 | +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ -| Mac OS X 10.7 Lion |Yes | 2.7 | 2.2.0 |x86-64 | +| Mac OS X 10.7 Lion |Yes | 2.6,2.7,3.2,3.3 | 2.2.0 |x86-64 | +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ | Redhat Linux 6 |Yes | 2.6 | |x86 | +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ | Ubuntu Linux 10.04 LTS |Yes | 2.6 | 2.2.0 |x86,x86-64 | +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ -| Ubuntu Linux 12.04 LTS |Yes | 2.6,2.7,3.2,3.3 | 2.2.0 |x86,x86-64 | +| Ubuntu Linux 12.04 LTS |Yes | 2.6,2.7,3.2,3.3,PyPy2.1 | 2.2.0 |x86,x86-64 | +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ | Raspian Wheezy |Yes | 2.7,3.2 | 2.2.0 |arm | +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ @@ -213,11 +232,9 @@ Current platform support for Pillow. Binary distributions are contributed for ea +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ | Windows Server 2008 R2 Enterprise|Yes | 3.3 | |x86-64 | +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ -| Windows 8 Pro |Yes | 2.6,2.7,3.2,3.3,PyPy1.9 [1]_ | 2.2.0 |x86 [2]_,x86-64 | +| Windows 8 Pro |Yes | 2.6,2.7,3.2,3.3,3.4a3 | 2.2.0 |x86,x86-64 | +----------------------------------+-------------+------------------------------+------------------------------+-----------------------+ -.. [1] x86 only, 2.1.0 tested -.. [2] In some cases, x86 support may indicate 32-bit compilation on 64-bit architecture (vs. compilation on 32-bit hardware). Port existing PIL-based code to Pillow ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/Tests/test_file_webp_metadata.py b/Tests/test_file_webp_metadata.py index 031865bd7..886011322 100644 --- a/Tests/test_file_webp_metadata.py +++ b/Tests/test_file_webp_metadata.py @@ -45,7 +45,8 @@ def test_write_exif_metadata(): webp_exif = webp_image.info.get('exif', None) assert_true(webp_exif) - assert_equal(webp_exif, expected_exif) + if webp_exif: + assert_equal(webp_exif, expected_exif, "Webp Exif didn't match") def test_read_icc_profile(): @@ -77,5 +78,7 @@ def test_write_icc_metadata(): webp_image = Image.open(buffer) webp_icc_profile = webp_image.info.get('icc_profile', None) + assert_true(webp_icc_profile) - assert_equal(webp_icc_profile, expected_icc_profile) + if webp_icc_profile: + assert_equal(webp_icc_profile, expected_icc_profile, "Webp ICC didn't match") diff --git a/Tests/test_image_transform.py b/Tests/test_image_transform.py index 31516d978..fdee6072f 100644 --- a/Tests/test_image_transform.py +++ b/Tests/test_image_transform.py @@ -57,6 +57,40 @@ def test_mesh(): assert_image_equal(blank, transformed.crop((w//2,0,w,h//2))) assert_image_equal(blank, transformed.crop((0,h//2,w//2,h))) +def _test_alpha_premult(op): + # create image with half white, half black, with the black half transparent. + # do op, + # there should be no darkness in the white section. + im = Image.new('RGBA', (10,10), (0,0,0,0)); + im2 = Image.new('RGBA', (5,10), (255,255,255,255)); + im.paste(im2, (0,0)) + + im = op(im, (40,10)) + im_background = Image.new('RGB', (40,10), (255,255,255)) + im_background.paste(im, (0,0), im) + + hist = im_background.histogram() + assert_equal(40*10, hist[-1]) + + +def test_alpha_premult_resize(): + + def op (im, sz): + return im.resize(sz, Image.LINEAR) + + _test_alpha_premult(op) + +def test_alpha_premult_transform(): + + def op(im, sz): + (w,h) = im.size + return im.transform(sz, Image.EXTENT, + (0,0, + w,h), + Image.BILINEAR) + + _test_alpha_premult(op) + def test_blank_fill(): # attempting to hit diff --git a/_webp.c b/_webp.c index 7f36670e3..a85551533 100644 --- a/_webp.c +++ b/_webp.c @@ -20,8 +20,8 @@ PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args) uint8_t *output; char *mode; Py_ssize_t size; - Py_ssize_t icc_size; - Py_ssize_t exif_size; + Py_ssize_t icc_size; + Py_ssize_t exif_size; size_t ret_size; if (!PyArg_ParseTuple(args, "s#iifss#s#", @@ -29,7 +29,7 @@ PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args) &icc_bytes, &icc_size, &exif_bytes, &exif_size)) { Py_RETURN_NONE; } - + if (strcmp(mode, "RGBA")==0){ if (size < width * height * 4){ Py_RETURN_NONE; @@ -52,8 +52,18 @@ PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args) } #else { + /* I want to truncate the *_size items that get passed into webp + data. Pypy2.1.0 had some issues where the Py_ssize_t items had + data in the upper byte. (Not sure why, it shouldn't have been there) + */ + int i_icc_size = (int)icc_size; + int i_exif_size = (int)exif_size; WebPData output_data = {0}; WebPData image = { output, ret_size }; + WebPData icc_profile = { icc_bytes, i_icc_size }; + WebPData exif = { exif_bytes, i_exif_size }; + WebPMuxError err; + int dbg = 0; int copy_data = 0; // value 1 indicates given data WILL be copied to the mux // and value 0 indicates data will NOT be copied. @@ -61,14 +71,36 @@ PyObject* WebPEncode_wrapper(PyObject* self, PyObject* args) WebPMux* mux = WebPMuxNew(); WebPMuxSetImage(mux, &image, copy_data); - if (icc_size > 0) { - WebPData icc_profile = { icc_bytes, icc_size }; - WebPMuxSetChunk(mux, "ICCP", &icc_profile, copy_data); + if (dbg) { + /* was getting %ld icc_size == 0, icc_size>0 was true */ + fprintf(stderr, "icc size %d, %d \n", i_icc_size, i_icc_size > 0); } - if (exif_size > 0) { - WebPData exif = { exif_bytes, exif_size }; - WebPMuxSetChunk(mux, "EXIF", &exif, copy_data); + if (i_icc_size > 0) { + if (dbg) { + fprintf (stderr, "Adding ICC Profile\n"); + } + err = WebPMuxSetChunk(mux, "ICCP", &icc_profile, copy_data); + if (dbg && err == WEBP_MUX_INVALID_ARGUMENT) { + fprintf(stderr, "Invalid ICC Argument\n"); + } else if (dbg && err == WEBP_MUX_MEMORY_ERROR) { + fprintf(stderr, "ICC Memory Error\n"); + } + } + + if (dbg) { + fprintf(stderr, "exif size %d \n", i_exif_size); + } + if (i_exif_size > 0) { + if (dbg){ + fprintf (stderr, "Adding Exif Data\n"); + } + err = WebPMuxSetChunk(mux, "EXIF", &exif, copy_data); + if (dbg && err == WEBP_MUX_INVALID_ARGUMENT) { + fprintf(stderr, "Invalid Exif Argument\n"); + } else if (dbg && err == WEBP_MUX_MEMORY_ERROR) { + fprintf(stderr, "Exif Memory Error\n"); + } } WebPMuxAssemble(mux, &output_data); diff --git a/docs/Guardfile b/docs/Guardfile new file mode 100644 index 000000000..2bbb2ef91 --- /dev/null +++ b/docs/Guardfile @@ -0,0 +1,9 @@ +#!/usr/bin/env python +from livereload.task import Task +from livereload.compiler import shell + +Task.add('*.rst', shell('make html')) +Task.add('*/*.rst', shell('make html')) +Task.add('_static/*.css', shell('make clean html')) +Task.add('Makefile', shell('make html')) +Task.add('conf.py', shell('make html')) diff --git a/docs/Makefile b/docs/Makefile index 6fd3002d5..f28f802a1 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -151,3 +151,6 @@ doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." + +livehtml: html + livereload $(BUILDDIR)/html -p 33233 diff --git a/docs/PIL.rst b/docs/PIL.rst index 870b896fa..8918fce0e 100644 --- a/docs/PIL.rst +++ b/docs/PIL.rst @@ -1,18 +1,10 @@ PIL Package =========== -:mod:`PIL` Package ------------------- +:mod:`Image` Module +------------------- -.. automodule:: PIL.__init__ - :members: - :undoc-members: - :show-inheritance: - -:mod:`ArgImagePlugin` Module ----------------------------- - -.. automodule:: PIL.ArgImagePlugin +.. automodule:: PIL.Image :members: :undoc-members: :show-inheritance: @@ -25,22 +17,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`BmpImagePlugin` Module ----------------------------- - -.. automodule:: PIL.BmpImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`BufrStubImagePlugin` Module ---------------------------------- - -.. automodule:: PIL.BufrStubImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`ContainerIO` Module ------------------------- @@ -49,30 +25,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`CurImagePlugin` Module ----------------------------- - -.. automodule:: PIL.CurImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`DcxImagePlugin` Module ----------------------------- - -.. automodule:: PIL.DcxImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`EpsImagePlugin` Module ----------------------------- - -.. automodule:: PIL.EpsImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`ExifTags` Module ---------------------- @@ -81,22 +33,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`FitsStubImagePlugin` Module ---------------------------------- - -.. automodule:: PIL.FitsStubImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`FliImagePlugin` Module ----------------------------- - -.. automodule:: PIL.FliImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`FontFile` Module ---------------------- @@ -105,22 +41,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`FpxImagePlugin` Module ----------------------------- - -.. automodule:: PIL.FpxImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`GbrImagePlugin` Module ----------------------------- - -.. automodule:: PIL.GbrImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`GdImageFile` Module ------------------------- @@ -129,14 +49,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`GifImagePlugin` Module ----------------------------- - -.. automodule:: PIL.GifImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`GimpGradientFile` Module ------------------------------ @@ -153,54 +65,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`GribStubImagePlugin` Module ---------------------------------- - -.. automodule:: PIL.GribStubImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`Hdf5StubImagePlugin` Module ---------------------------------- - -.. automodule:: PIL.Hdf5StubImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`IcnsImagePlugin` Module ------------------------------ - -.. automodule:: PIL.IcnsImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`IcoImagePlugin` Module ----------------------------- - -.. automodule:: PIL.IcoImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`ImImagePlugin` Module ---------------------------- - -.. automodule:: PIL.ImImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`Image` Module -------------------- - -.. automodule:: PIL.Image - :members: - :undoc-members: - :show-inheritance: - :mod:`ImageChops` Module ------------------------ @@ -377,30 +241,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`ImtImagePlugin` Module ----------------------------- - -.. automodule:: PIL.ImtImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`IptcImagePlugin` Module ------------------------------ - -.. automodule:: PIL.IptcImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`JpegImagePlugin` Module ------------------------------ - -.. automodule:: PIL.JpegImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`JpegPresets` Module ------------------------- @@ -409,38 +249,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`McIdasImagePlugin` Module -------------------------------- - -.. automodule:: PIL.McIdasImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`MicImagePlugin` Module ----------------------------- - -.. automodule:: PIL.MicImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`MpegImagePlugin` Module ------------------------------ - -.. automodule:: PIL.MpegImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`MspImagePlugin` Module ----------------------------- - -.. automodule:: PIL.MspImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`OleFileIO` Module ----------------------- @@ -465,22 +273,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`PalmImagePlugin` Module ------------------------------ - -.. automodule:: PIL.PalmImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`PcdImagePlugin` Module ----------------------------- - -.. automodule:: PIL.PcdImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`PcfFontFile` Module ------------------------- @@ -489,78 +281,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`PcxImagePlugin` Module ----------------------------- - -.. automodule:: PIL.PcxImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`PdfImagePlugin` Module ----------------------------- - -.. automodule:: PIL.PdfImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`PixarImagePlugin` Module ------------------------------- - -.. automodule:: PIL.PixarImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`PngImagePlugin` Module ----------------------------- - -.. automodule:: PIL.PngImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`PpmImagePlugin` Module ----------------------------- - -.. automodule:: PIL.PpmImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`PsdImagePlugin` Module ----------------------------- - -.. automodule:: PIL.PsdImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`SgiImagePlugin` Module ----------------------------- - -.. automodule:: PIL.SgiImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`SpiderImagePlugin` Module -------------------------------- - -.. automodule:: PIL.SpiderImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`SunImagePlugin` Module ----------------------------- - -.. automodule:: PIL.SunImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`TarIO` Module ------------------- @@ -569,22 +289,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`TgaImagePlugin` Module ----------------------------- - -.. automodule:: PIL.TgaImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`TiffImagePlugin` Module ------------------------------ - -.. automodule:: PIL.TiffImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`TiffTags` Module ---------------------- @@ -601,46 +305,6 @@ PIL Package :undoc-members: :show-inheritance: -:mod:`WebPImagePlugin` Module ------------------------------ - -.. automodule:: PIL.WebPImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`WmfImagePlugin` Module ----------------------------- - -.. automodule:: PIL.WmfImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`XVThumbImagePlugin` Module --------------------------------- - -.. automodule:: PIL.XVThumbImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`XbmImagePlugin` Module ----------------------------- - -.. automodule:: PIL.XbmImagePlugin - :members: - :undoc-members: - :show-inheritance: - -:mod:`XpmImagePlugin` Module ----------------------------- - -.. automodule:: PIL.XpmImagePlugin - :members: - :undoc-members: - :show-inheritance: - :mod:`_binary` Module --------------------- diff --git a/docs/conf.py b/docs/conf.py index 972984f82..a9ae431bb 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -17,6 +17,7 @@ import sys, os # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../')) +import PIL # -- General configuration ----------------------------------------------------- @@ -25,7 +26,9 @@ sys.path.insert(0, os.path.abspath('../')) # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', + 'sphinx.ext.intersphinx'] +intersphinx_mapping = {'http://docs.python.org/2/': None} # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] @@ -48,9 +51,9 @@ copyright = u'1997-2011 by Secret Labs AB, 1995-2011 by Fredrik Lundh, 2010-2013 # built documents. # # The short X.Y version. -version = '2.2.0' +version = PIL.PILLOW_VERSION # The full version, including alpha/beta/rc tags. -release = '2.2.0' +release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. @@ -64,7 +67,7 @@ release = '2.2.0' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ['_build', 'plugins.rst'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None @@ -89,80 +92,28 @@ pygments_style = 'sphinx' # -- Options for HTML output --------------------------------------------------- -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -html_theme = 'default' +from better import better_theme_path +html_theme_path = [better_theme_path] +html_theme = 'better' + +html_title = "Pillow v{release} (PIL fork)".format(release=release) +html_short_title = "Home" +html_static_path = ['_static'] # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} +html_theme_options = {} -# Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +html_sidebars = { + '**': ['localtoc.html', 'sourcelink.html', 'searchbox.html'], + 'index': ['searchbox.html'], +} # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None -# A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None - -# The name of an image file (relative to this directory) to place at the top -# of the sidebar. -#html_logo = None - -# The name of an image file (within the static path) to use as favicon of the -# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 -# pixels large. -#html_favicon = None - -# Add any paths that contain custom static files (such as style sheets) here, -# relative to this directory. They are copied after the builtin static files, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] - -# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, -# using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' - -# If true, SmartyPants will be used to convert quotes and dashes to -# typographically correct entities. -#html_use_smartypants = True - -# Custom sidebar templates, maps document names to template names. -#html_sidebars = {} - -# Additional templates that should be rendered to pages, maps page names to -# template names. -#html_additional_pages = {} - -# If false, no module index is generated. -#html_domain_indices = True - -# If false, no index is generated. -#html_use_index = True - -# If true, the index is split into individual pages for each letter. -#html_split_index = False - -# If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True - -# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True - -# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True - -# If true, an OpenSearch description file will be output, and all pages will -# contain a tag referring to it. The value of this option must be the -# base URL from which the finished HTML is served. -#html_use_opensearch = '' - -# This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None - # Output file base name for HTML help builder. htmlhelp_basename = 'PillowPILforkdoc' @@ -283,3 +234,13 @@ epub_copyright = u'2013, Author' # Allow duplicate toc entries. #epub_tocdup = True + +# skip_api_docs setting will skip PIL.rst if True. Used for working on the +# guides; makes livereload basically instantaneous. +def setup(app): + app.add_config_value('skip_api_docs', False, True) + +skip_api_docs = False + +if skip_api_docs: + exclude_patterns += ['PIL.rst'] diff --git a/docs/handbook/appendices.rst b/docs/handbook/appendices.rst new file mode 100644 index 000000000..f5482ffcd --- /dev/null +++ b/docs/handbook/appendices.rst @@ -0,0 +1,8 @@ +Appendices +========== + +.. toctree:: + :maxdepth: 2 + + image-file-formats + writing-your-own-file-decoder diff --git a/docs/handbook/concepts.rst b/docs/handbook/concepts.rst new file mode 100644 index 000000000..93f964e41 --- /dev/null +++ b/docs/handbook/concepts.rst @@ -0,0 +1,109 @@ +Concepts +======== + +The Python Imaging Library handles *raster images*; that is, rectangles of +pixel data. + +Bands +----- + +An image can consist of one or more bands of data. The Python Imaging Library +allows you to store several bands in a single image, provided they all have the +same dimensions and depth. + +To get the number and names of bands in an image, use the +:py:meth:`~PIL.Image.Image.getbands` method. + +Mode +---- + +The :term:`mode` of an image defines the type and depth of a pixel in the +image. The current release supports the following standard modes: + + * ``1`` (1-bit pixels, black and white, stored with one pixel per byte) + * ``L`` (8-bit pixels, black and white) + * ``P`` (8-bit pixels, mapped to any other mode using a color palette) + * ``RGB`` (3x8-bit pixels, true color) + * ``RGBA`` (4x8-bit pixels, true color with transparency mask) + * ``CMYK`` (4x8-bit pixels, color separation) + * ``YCbCr`` (3x8-bit pixels, color video format) + * ``I`` (32-bit signed integer pixels) + * ``F`` (32-bit floating point pixels) + +PIL also provides limited support for a few special modes, including ``LA`` (L +with alpha), ``RGBX`` (true color with padding) and ``RGBa`` (true color with +premultiplied alpha). However, PIL doesn’t support user-defined modes; if you +to handle band combinations that are not listed above, use a sequence of Image +objects. + +You can read the mode of an image through the :py:attr:`~PIL.Image.Image.mode` +attribute. This is a string containing one of the above values. + +Size +---- + +You can read the image size through the :py:attr:`~PIL.Image.Image.size` +attribute. This is a 2-tuple, containing the horizontal and vertical size in +pixels. + +Coordinate System +----------------- + +The Python Imaging Library uses a Cartesian pixel coordinate system, with (0,0) +in the upper left corner. Note that the coordinates refer to the implied pixel +corners; the centre of a pixel addressed as (0, 0) actually lies at (0.5, 0.5). + +Coordinates are usually passed to the library as 2-tuples (x, y). Rectangles +are represented as 4-tuples, with the upper left corner given first. For +example, a rectangle covering all of an 800x600 pixel image is written as (0, +0, 800, 600). + +Palette +------- + +The palette mode (``P``) uses a color palette to define the actual color for +each pixel. + +Info +---- + +You can attach auxiliary information to an image using the +:py:attr:`~PIL.Image.Image.info` attribute. This is a dictionary object. + +How such information is handled when loading and saving image files is up to +the file format handler (see the chapter on :ref:`image-file-formats`). Most +handlers add properties to the :py:attr:`~PIL.Image.Image.info` attribute when +loading an image, but ignore it when saving images. + +Filters +------- + +For geometry operations that may map multiple input pixels to a single output +pixel, the Python Imaging Library provides four different resampling *filters*. + +``NEAREST`` + Pick the nearest pixel from the input image. Ignore all other input pixels. + +``BILINEAR`` + Use linear interpolation over a 2x2 environment in the input image. Note + that in the current version of PIL, this filter uses a fixed input + environment when downsampling. + +``BICUBIC`` + Use cubic interpolation over a 4x4 environment in the input image. Note + that in the current version of PIL, this filter uses a fixed input + environment when downsampling. + +``ANTIALIAS`` + Calculate the output pixel value using a high-quality resampling filter (a + truncated sinc) on all pixels that may contribute to the output value. In + the current version of PIL, this filter can only be used with the resize + and thumbnail methods. + + .. versionadded:: 1.1.3 + +Note that in the current version of PIL, the ``ANTIALIAS`` filter is the only +filter that behaves properly when downsampling (that is, when converting a +large image to a small one). The ``BILINEAR`` and ``BICUBIC`` filters use a +fixed input environment, and are best used for scale-preserving geometric +transforms and upsamping. diff --git a/docs/handbook/guides.rst b/docs/handbook/guides.rst new file mode 100644 index 000000000..edec8bea8 --- /dev/null +++ b/docs/handbook/guides.rst @@ -0,0 +1,9 @@ +Guides +====== + +.. toctree:: + :maxdepth: 2 + + overview + tutorial + concepts diff --git a/docs/handbook/image-file-formats.rst b/docs/handbook/image-file-formats.rst new file mode 100644 index 000000000..8789e115a --- /dev/null +++ b/docs/handbook/image-file-formats.rst @@ -0,0 +1,534 @@ +.. _image-file-formats: + +Image file formats +================== + +The Python Imaging Library supports a wide variety of raster file formats. +Nearly 30 different file formats can be identified and read by the library. +Write support is less extensive, but most common interchange and presentation +formats are supported. + +The :py:meth:`~PIL.Image.Image.open` function identifies files from their +contents, not their names, but the :py:meth:`~PIL.Image.Image.save` method +looks at the name to determine which format to use, unless the format is given +explicitly. + +Fully supported formats +----------------------- + +BMP +^^^ + +PIL reads and writes Windows and OS/2 BMP files containing ``1``, ``L``, ``P``, +or ``RGB`` data. 16-colour images are read as ``P`` images. Run-length encoding +is not supported. + +The :py:meth:`~PIL.Image.Image.open` method sets the following +:py:attr:`~PIL.Image.Image.info` properties: + +**compression** + Set to ``bmp_rle`` if the file is run-length encoded. + +EPS +^^^ + +PIL identifies EPS files containing image data, and can read files that contain +embedded raster images (ImageData descriptors). If Ghostscript is available, +other EPS files can be read as well. The EPS driver can also write EPS images. + +GIF +^^^ + +PIL reads GIF87a and GIF89a versions of the GIF file format. The library writes +run-length encoded GIF87a files. Note that GIF files are always read as +grayscale (``L``) or palette mode (``P``) images. + +The :py:meth:`~PIL.Image.Image.open` method sets the following +:py:attr:`~PIL.Image.Image.info` properties: + +**background** + Default background color (a palette color index). + +**duration** + Time between frames in an animation (in milliseconds). + +**transparency** + Transparency color index. This key is omitted if the image is not + transparent. + +**version** + Version (either ``GIF87a`` or ``GIF89a``). + +Reading sequences +~~~~~~~~~~~~~~~~~ + +The GIF loader supports the :py:meth:`~file.seek` and :py:meth:`~file.tell` +methods. You can seek to the next frame (``im.seek(im.tell() + 1``), or rewind +the file by seeking to the first frame. Random access is not supported. + +Reading local images +~~~~~~~~~~~~~~~~~~~~ + +The GIF loader creates an image memory the same size as the GIF file’s *logical +screen size*, and pastes the actual pixel data (the *local image*) into this +image. If you only want the actual pixel rectangle, you can manipulate the +:py:attr:`~PIL.Image.Image.size` and :py:attr:`~PIL.Image.Image.tile` +attributes before loading the file:: + + im = Image.open(...) + + if im.tile[0][0] == "gif": + # only read the first "local image" from this GIF file + tag, (x0, y0, x1, y1), offset, extra = im.tile[0] + im.size = (x1 - x0, y1 - y0) + im.tile = [(tag, (0, 0) + im.size, offset, extra)] + +IM +^^ + +IM is a format used by LabEye and other applications based on the IFUNC image +processing library. The library reads and writes most uncompressed interchange +versions of this format. + +IM is the only format that can store all internal PIL formats. + +JPEG +^^^^ + +PIL reads JPEG, JFIF, and Adobe JPEG files containing ``L``, ``RGB``, or +``CMYK`` data. It writes standard and progressive JFIF files. + +Using the :py:meth:`~PIL.Image.Image.draft` method, you can speed things up by +converting ``RGB`` images to ``L``, and resize images to 1/2, 1/4 or 1/8 of +their original size while loading them. The :py:meth:`~PIL.Image.Image.draft` +method also configures the JPEG decoder to trade some quality for speed. + +The :py:meth:`~PIL.Image.Image.open` method sets the following +:py:attr:`~PIL.Image.Image.info` properties: + +**jfif** + JFIF application marker found. If the file is not a JFIF file, this key is + not present. + +**adobe** + Adobe application marker found. If the file is not an Adobe JPEG file, this + key is not present. + +**progression** + Indicates that this is a progressive JPEG file. + +The :py:meth:`~PIL.Image.Image.save` method supports the following options: + +**quality** + The image quality, on a scale from 1 (worst) to 95 (best). The default is + 75. Values above 95 should be avoided; 100 disables portions of the JPEG + compression algorithm, and results in large files with hardly any gain in = + image quality. + +**optimize** + If present, indicates that the encoder should make an extra pass over the + image in order to select optimal encoder settings. + +**progressive** + If present, indicates that this image should be stored as a progressive + JPEG file. + +.. note:: + + To enable JPEG support, you need to build and install the IJG JPEG library + before building the Python Imaging Library. See the distribution README for + details. + +MSP +^^^ + +PIL identifies and reads MSP files from Windows 1 and 2. The library writes +uncompressed (Windows 1) versions of this format. + +PCX +^^^ + +PIL reads and writes PCX files containing ``1``, ``L``, ``P``, or ``RGB`` data. + +PNG +^^^ + +PIL identifies, reads, and writes PNG files containing ``1``, ``L``, ``P``, +``RGB``, or ``RGBA`` data. Interlaced files are supported as of v1.1.7. + +The :py:meth:`~PIL.Image.Image.open` method sets the following +:py:attr:`~PIL.Image.Image.info` properties, when appropriate: + +**gamma** + Gamma, given as a floating point number. + +**transparency** + Transparency color index. This key is omitted if the image is not a + transparent palette image. + +The :py:meth:`~PIL.Image.Image.save` method supports the following options: + +**optimize** + If present, instructs the PNG writer to make the output file as small as + possible. This includes extra processing in order to find optimal encoder + settings. + +**transparency** + For ``P`` and ``L`` images, this option controls what color image to mark as + transparent. + +**bits (experimental)** + For ``P`` images, this option controls how many bits to store. If omitted, + the PNG writer uses 8 bits (256 colors). + +**dictionary (experimental)** + Set the ZLIB encoder dictionary. + +.. note:: + + To enable PNG support, you need to build and install the ZLIB compression + library before building the Python Imaging Library. See the distribution + README for details. + +PPM +^^^ + +PIL reads and writes PBM, PGM and PPM files containing ``1``, ``L`` or ``RGB`` +data. + +SPIDER +^^^^^^ + +PIL reads and writes SPIDER image files of 32-bit floating point data +("F;32F"). + +PIL also reads SPIDER stack files containing sequences of SPIDER images. The +:py:meth:`~file.seek` and :py:meth:`~file.tell` methods are supported, and +random access is allowed. + +The :py:meth:`~PIL.Image.Image.open` method sets the following attributes: + +**format** + Set to ``SPIDER`` + +**istack** + Set to 1 if the file is an image stack, else 0. + +**nimages** + Set to the number of images in the stack. + +A convenience method, :py:meth:`~PIL.Image.Image.convert2byte`, is provided for +converting floating point data to byte data (mode ``L``):: + + im = Image.open('image001.spi').convert2byte() + +Writing files in SPIDER format +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The extension of SPIDER files may be any 3 alphanumeric characters. Therefore +the output format must be specified explicitly:: + + im.save('newimage.spi', format='SPIDER') + +For more information about the SPIDER image processing package, see the +`SPIDER home page`_ at `Wadsworth Center`_. + +.. _SPIDER home page: http://www.wadsworth.org/spider_doc/spider/docs/master.html +.. _Wadsworth Center: http://www.wadsworth.org/ + +TIFF +^^^^ + +PIL reads and writes TIFF files. It can read both striped and tiled images, +pixel and plane interleaved multi-band images, and either uncompressed, or +Packbits, LZW, or JPEG compressed images. + +If you have libtiff and its headers installed, PIL can read and write many more +kinds of compressed TIFF files. If not, PIL will always write uncompressed +files. + +The :py:meth:`~PIL.Image.Image.open` method sets the following +:py:attr:`~PIL.Image.Image.info` properties: + +**compression** + Compression mode. + +**dpi** + Image resolution as an (xdpi, ydpi) tuple, where applicable. You can use + the :py:attr:`~PIL.Image.Image.tag` attribute to get more detailed + information about the image resolution. + + .. versionadded:: 1.1.5 + +In addition, the :py:attr:`~PIL.Image.Image.tag` attribute contains a +dictionary of decoded TIFF fields. Values are stored as either strings or +tuples. Note that only short, long and ASCII tags are correctly unpacked by +this release. + +WebP +^^^^ + +PIL reads and writes WebP files. The specifics of PIL's capabilities with this +format are currently undocumented. + +XBM +^^^ + +PIL reads and writes X bitmap files (mode ``1``). + +XV Thumbnails +^^^^^^^^^^^^^ + +PIL can read XV thumbnail files. + +Read-only formats +----------------- + +CUR +^^^ + +CUR is used to store cursors on Windows. The CUR decoder reads the largest +available cursor. Animated cursors are not supported. + +DCX +^^^ + +DCX is a container file format for PCX files, defined by Intel. The DCX format +is commonly used in fax applications. The DCX decoder can read files containing +``1``, ``L``, ``P``, or ``RGB`` data. + +When the file is opened, only the first image is read. You can use +:py:meth:`~file.seek` or :py:mod:`~PIL.ImageSequence` to read other images. + +FLI, FLC +^^^^^^^^ + +PIL reads Autodesk FLI and FLC animations. + +The :py:meth:`~PIL.Image.Image.open` method sets the following +:py:attr:`~PIL.Image.Image.info` properties: + +**duration** + The delay (in milliseconds) between each frame. + +FPX +^^^ + +PIL reads Kodak FlashPix files. In the current version, only the highest +resolution image is read from the file, and the viewing transform is not taken +into account. + +.. note:: + + To enable full FlashPix support, you need to build and install the IJG JPEG + library before building the Python Imaging Library. See the distribution + README for details. + +GBR +^^^ + +The GBR decoder reads GIMP brush files. + +The :py:meth:`~PIL.Image.Image.open` method sets the following +:py:attr:`~PIL.Image.Image.info` properties: + +**description** + The brush name. + +GD +^^ + +PIL reads uncompressed GD files. Note that this file format cannot be +automatically identified, so you must use :py:func:`PIL.GdImageFile.open` to +read such a file. + +The :py:meth:`~PIL.Image.Image.open` method sets the following +:py:attr:`~PIL.Image.Image.info` properties: + +**transparency** + Transparency color index. This key is omitted if the image is not + transparent. + +ICO +^^^ + +ICO is used to store icons on Windows. The largest available icon is read. + +IMT +^^^ + +PIL reads Image Tools images containing ``L`` data. + +IPTC/NAA +^^^^^^^^ + +PIL provides limited read support for IPTC/NAA newsphoto files. + +MCIDAS +^^^^^^ + +PIL identifies and reads 8-bit McIdas area files. + +MIC (read only) + +PIL identifies and reads Microsoft Image Composer (MIC) files. When opened, the +first sprite in the file is loaded. You can use :py:meth:`~file.seek` and +:py:meth:`~file.tell` to read other sprites from the file. + +PCD +^^^ + +PIL reads PhotoCD files containing ``RGB`` data. By default, the 768x512 +resolution is read. You can use the :py:meth:`~PIL.Image.Image.draft` method to +read the lower resolution versions instead, thus effectively resizing the image +to 384x256 or 192x128. Higher resolutions cannot be read by the Python Imaging +Library. + +PSD +^^^ + +PIL identifies and reads PSD files written by Adobe Photoshop 2.5 and 3.0. + +SGI +^^^ + +PIL reads uncompressed ``L``, ``RGB``, and ``RGBA`` files. + +TGA +^^^ + +PIL reads 24- and 32-bit uncompressed and run-length encoded TGA files. + +WAL +^^^ + +.. versionadded:: 1.1.4 + +PIL reads Quake2 WAL texture files. + +Note that this file format cannot be automatically identified, so you must use +the open function in the :py:mod:`~PIL.WalImageFile` module to read files in +this format. + +By default, a Quake2 standard palette is attached to the texture. To override +the palette, use the putpalette method. + +XPM +^^^ + +PIL reads X pixmap files (mode ``P``) with 256 colors or less. + +The :py:meth:`~PIL.Image.Image.open` method sets the following +:py:attr:`~PIL.Image.Image.info` properties: + +**transparency** + Transparency color index. This key is omitted if the image is not + transparent. + +Write-only formats +------------------ + +PALM +^^^^ + +PIL provides write-only support for PALM pixmap files. + +The format code is ``Palm``, the extension is ``.palm``. + +PDF +^^^ + +PIL can write PDF (Acrobat) images. Such images are written as binary PDF 1.1 +files, using either JPEG or HEX encoding depending on the image mode (and +whether JPEG support is available or not). + +PIXAR (read only) + +PIL provides limited support for PIXAR raster files. The library can identify +and read “dumped” RGB files. + +The format code is ``PIXAR``. + +Identify-only formats +--------------------- + +BUFR +^^^^ + +.. versionadded:: 1.1.3 + +PIL provides a stub driver for BUFR files. + +To add read or write support to your application, use +:py:func:`PIL.BufrStubImagePlugin.register_handler`. + +FITS +^^^^ + +.. versionadded:: 1.1.5 + +PIL provides a stub driver for FITS files. + +To add read or write support to your application, use +:py:func:`PIL.FitsStubImagePlugin.register_handler`. + +GRIB +^^^^ + +.. versionadded:: 1.1.5 + +PIL provides a stub driver for GRIB files. + +The driver requires the file to start with a GRIB header. If you have files +with embedded GRIB data, or files with multiple GRIB fields, your application +has to seek to the header before passing the file handle to PIL. + +To add read or write support to your application, use +:py:func:`PIL.GribStubImagePlugin.register_handler`. + +HDF5 +^^^^ + +.. versionadded:: 1.1.5 + +PIL provides a stub driver for HDF5 files. + +To add read or write support to your application, use +:py:func:`PIL.Hdf5StubImagePlugin.register_handler`. + +MPEG +^^^^ + +PIL identifies MPEG files. + +WMF +^^^ + +PIL can identify placable WMF files. + +In PIL 1.1.4 and earlier, the WMF driver provides some limited rendering +support, but not enough to be useful for any real application. + +In PIL 1.1.5 and later, the WMF driver is a stub driver. To add WMF read or +write support to your application, use +:py:func:`PIL.WmfImagePlugin.register_handler` to register a WMF handler. + +:: + + from PIL import Image + from PIL import WmfImagePlugin + + class WmfHandler: + def open(self, im): + ... + def load(self, im): + ... + return image + def save(self, im, fp, filename): + ... + + wmf_handler = WmfHandler() + + WmfImagePlugin.register_handler(wmf_handler) + + im = Image.open("sample.wmf") diff --git a/docs/handbook/overview.rst b/docs/handbook/overview.rst new file mode 100644 index 000000000..f1c26e616 --- /dev/null +++ b/docs/handbook/overview.rst @@ -0,0 +1,46 @@ +Overview +======== + +The **Python Imaging Library** adds image processing capabilities to your +Python interpreter. + +This library provides extensive file format support, an efficient internal +representation, and fairly powerful image processing capabilities. + +The core image library is designed for fast access to data stored in a few +basic pixel formats. It should provide a solid foundation for a general image +processing tool. + +Let’s look at a few possible uses of this library. + +Image Archives +-------------- + +The Python Imaging Library is ideal for for image archival and batch processing +applications. You can use the library to create thumbnails, convert between +file formats, print images, etc. + +The current version identifies and reads a large number of formats. Write +support is intentionally restricted to the most commonly used interchange and +presentation formats. + +Image Display +------------- + +The current release includes Tk :py:class:`~PIL.ImageTk.PhotoImage` and +:py:class:`~PIL.ImageTk.BitmapImage` interfaces, as well as a :py:mod:`Windows +DIB interface ` that can be used with PythonWin and other +Windows-based toolkits. Many other GUI toolkits come with some kind of PIL +support. + +For debugging, there’s also a :py:meth:`show` method which saves an image to +disk, and calls an external display utility. + +Image Processing +---------------- + +The library contains basic image processing functionality, including point operations, filtering with a set of built-in convolution kernels, and colour space conversions. + +The library also supports image resizing, rotation and arbitrary affine transforms. + +There’s a histogram method allowing you to pull some statistics out of an image. This can be used for automatic contrast enhancement, and for global statistical analysis. diff --git a/docs/handbook/tutorial.rst b/docs/handbook/tutorial.rst new file mode 100644 index 000000000..d7bb98386 --- /dev/null +++ b/docs/handbook/tutorial.rst @@ -0,0 +1,539 @@ +Tutorial +======== + +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 + >>> im = Image.open("lena.ppm") + +If successful, this function returns an :py:class:`~PIL.Image.Image` object. +You can now use instance attributes to examine the file contents:: + + >>> from __future__ import print_function + >>> print(im.format, im.size, im.mode) + 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” +(luminance) for greyscale images, “RGB” for true color images, and “CMYK” for +pre-press images. + +If the file cannot be opened, an :py:exc:`IOError` exception is raised. + +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 + efficient, since it saves the image to a temporary file and calls the + :command:`xv` utility to display the image. If you don’t have :command:`xv` + installed, it won’t even work. When it does work though, it is very handy + for debugging and tests. + +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 +^^^^^^^^^^^^^^^^^^^^^ + +:: + + from __future__ import print_function + 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: + Image.open(infile).save(outfile) + except IOError: + print("cannot convert", infile) + +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 +^^^^^^^^^^^^^^^^^^^^^^ + +:: + + from __future__ import print_function + 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: + im = Image.open(infile) + im.thumbnail(size) + im.save(outfile, "JPEG") + except IOError: + print("cannot create thumbnail for", infile) + + +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 +^^^^^^^^^^^^^^^^^^^^ + +:: + + from __future__ import print_function + import sys + from PIL import Image + + for infile in sys.argv[1:]: + try: + im = Image.open(infile) + print(infile, im.format, "%dx%d" % im.size, im.mode) + except IOError: + 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 +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + region = region.transpose(Image.ROTATE_180) + 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 +^^^^^^^^^^^^^^^^ + +:: + + def roll(image, delta): + "Roll an image sideways" + + xsize, ysize = image.size + + delta = delta % xsize + if delta == 0: return image + + part1 = image.crop((0, 0, delta, ysize)) + part2 = image.crop((delta, 0, xsize, ysize)) + image.paste(part2, (0, 0, xsize-delta, ysize)) + image.paste(part1, (xsize-delta, 0, xsize, ysize)) + + return image + +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 +in-between indicate different levels of transparency. + +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 +the image itself. To work with individual color bands, you may want to convert +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 +^^^^^^^^^^^^^^^^^^^^ + +:: + + out = im.transpose(Image.FLIP_LEFT_RIGHT) + out = im.transpose(Image.FLIP_TOP_BOTTOM) + out = im.transpose(Image.ROTATE_90) + out = im.transpose(Image.ROTATE_180) + out = im.transpose(Image.ROTATE_270) + +There’s no difference in performance or result between ``transpose(ROTATE)`` +and corresponding :py:meth:`~PIL.Image.Image.rotate` operations. + +A more general form of image transformations can be carried out via the +:py:meth:`~PIL.Image.Image.transform` method. + +.. _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 +^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + im = Image.open("lena.ppm").convert("L") + +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 +function object expecting one argument can be passed to the this method. Each +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. + +You can adjust contrast, brightness, color balance and sharpness in this way. + +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 + + im = Image.open("animation.gif") + im.seek(1) # skip to the second frame + + try: + while 1: + im.seek(im.tell()+1) + # do something to im + except EOFError: + pass # end of sequence + +As seen in this example, you’ll get an :py:exc:`EOFError` exception when the +sequence ends. + +Note that most drivers in the current version of the library only allow you to +seek to the next frame (as in the above example). To rewind the file, you may +have to reopen it. + +The following iterator class lets you to use the for-statement to loop over the +sequence: + +A sequence iterator class +^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + class ImageSequence: + def __init__(self, im): + self.im = im + def __getitem__(self, ix): + try: + if ix: + self.im.seek(ix) + return self.im + except EOFError: + raise IndexError # end of sequence + + for frame in ImageSequence(im): + # ...do something to frame... + + +Postscript printing +------------------- + +The Python Imaging Library includes functions to print images, text and +graphics on Postscript printers. Here’s a simple example: + +Drawing Postscript +^^^^^^^^^^^^^^^^^^ + +:: + + from PIL import Image + from PIL import PSDraw + + im = Image.open("lena.ppm") + title = "lena" + box = (1*72, 2*72, 7*72, 10*72) # in points + + ps = PSDraw.PSDraw() # default is sys.stdout + ps.begin_document(title) + + # draw the image (75 dpi) + ps.image(box, im, 75) + ps.rectangle(box) + + # draw centered title + ps.setfont("HelveticaNarrow-Bold", 36) + w, h, b = ps.textsize(title) + ps.text((4*72-w/2, 1*72-h), title) + + ps.end_document() + +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 +simply pass it the filename as an argument:: + + im = Image.open("lena.ppm") + +If everything goes well, the result is an :py:class:`PIL.Image.Image` object. +Otherwise, an :exc:`IOError` exception is raised. + +You can use a file-like object instead of the filename. The object must +implement :py:meth:`~file.read`, :py:meth:`~file.seek` and +:py:meth:`~file.tell` methods, and be opened in binary mode. + +Reading from an open file +^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + fp = open("lena.ppm", "rb") + im = Image.open(fp) + +To read an image from string data, use the :py:class:`~StringIO.StringIO` +class: + +Reading from a string +^^^^^^^^^^^^^^^^^^^^^ + +:: + + import StringIO + + im = Image.open(StringIO.StringIO(buffer)) + +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. + +Reading from a tar archive +^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + from PIL import TarIO + + fp = TarIO.TarIO("Imaging.tar", "Imaging/test/lena.ppm") + im = Image.open(fp) + +Controlling the decoder +----------------------- + +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 +laser printer (when only a greyscale version of the image is needed). + +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 +^^^^^^^^^^^^^^^^^^^^^ + +:: + + from __future__ import print_function + im = Image.open(file) + print("original =", im.mode, im.size) + + im.draft("L", (100, 100)) + print("draft =", im.mode, im.size) + +This prints something like:: + + 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. diff --git a/docs/handbook/writing-your-own-file-decoder.rst b/docs/handbook/writing-your-own-file-decoder.rst new file mode 100644 index 000000000..caf9dc07e --- /dev/null +++ b/docs/handbook/writing-your-own-file-decoder.rst @@ -0,0 +1,278 @@ +Writing your own file decoder +============================= + +The Python Imaging Library uses a plug-in model which allows you to add your +own decoders to the library, without any changes to the library itself. Such +plug-ins have names like :file:`XxxImagePlugin.py`, where ``Xxx`` is a unique +format name (usually an abbreviation). + +A decoder plug-in should contain a decoder class, based on the +:py:class:`PIL.ImageFile.ImageFile` base class. This class should provide an +:py:meth:`_open` method, which reads the file header and sets up at least the +:py:attr:`~PIL.Image.Image.mode` and :py:attr:`~PIL.Image.Image.size` +attributes. To be able to load the file, the method must also create a list of +:py:attr:`tile` descriptors. The class must be explicitly registered, via a +call to the :py:mod:`~PIL.Image` module. + +For performance reasons, it is important that the :py:meth:`_open` method +quickly rejects files that do not have the appropriate contents. + +Example +------- + +The following plug-in supports a simple format, which has a 128-byte header +consisting of the words “SPAM” followed by the width, height, and pixel size in +bits. The header fields are separated by spaces. The image data follows +directly after the header, and can be either bi-level, greyscale, or 24-bit +true color. + +**SpamImagePlugin.py**:: + + from PIL import Image, ImageFile + import string + + class SpamImageFile(ImageFile.ImageFile): + + format = "SPAM" + format_description = "Spam raster image" + + def _open(self): + + # check header + header = self.fp.read(128) + if header[:4] != "SPAM": + raise SyntaxError, "not a SPAM file" + + header = string.split(header) + + # size in pixels (width, height) + self.size = int(header[1]), int(header[2]) + + # mode setting + bits = int(header[3]) + if bits == 1: + self.mode = "1" + elif bits == 8: + self.mode = "L" + elif bits == 24: + self.mode = "RGB" + else: + raise SyntaxError, "unknown number of bits" + + # data descriptor + self.tile = [ + ("raw", (0, 0) + self.size, 128, (self.mode, 0, 1)) + ] + + Image.register_open("SPAM", SpamImageFile) + + Image.register_extension("SPAM", ".spam") + Image.register_extension("SPAM", ".spa") # dos version + +The format handler must always set the :py:attr:`~PIL.Image.Image.size` and +:py:attr:`~PIL.Image.Image.mode` attributes. If these are not set, the file +cannot be opened. To simplify the decoder, the calling code considers +exceptions like :py:exc:`SyntaxError`, :py:exc:`KeyError`, and +:py:exc:`IndexError`, as a failure to identify the file. + +Note that the decoder must be explicitly registered using +:py:func:`PIL.Image.register_open`. Although not required, it is also a good +idea to register any extensions used by this format. + +The :py:attr:`tile` attribute +----------------------------- + +To be able to read the file as well as just identifying it, the :py:attr:`tile` +attribute must also be set. This attribute consists of a list of tile +descriptors, where each descriptor specifies how data should be loaded to a +given region in the image. In most cases, only a single descriptor is used, +covering the full image. + +The tile descriptor is a 4-tuple with the following contents:: + + (decoder, region, offset, parameters) + +The fields are used as follows: + +**decoder** + Specifies which decoder to use. The ``raw`` decoder used here supports + uncompressed data, in a variety of pixel formats. For more information on + this decoder, see the description below. + +**region** + A 4-tuple specifying where to store data in the image. + +**offset** + Byte offset from the beginning of the file to image data. + +**parameters** + Parameters to the decoder. The contents of this field depends on the + decoder specified by the first field in the tile descriptor tuple. If the + decoder doesn’t need any parameters, use None for this field. + +Note that the :py:attr:`tile` attribute contains a list of tile descriptors, +not just a single descriptor. + +The ``raw`` decoder + +The ``raw`` decoder is used to read uncompressed data from an image file. It +can be used with most uncompressed file formats, such as PPM, BMP, uncompressed +TIFF, and many others. To use the raw decoder with the +:py:func:`PIL.Image.fromstring` function, use the following syntax:: + + image = Image.fromstring( + mode, size, data, "raw", + raw mode, stride, orientation + ) + +When used in a tile descriptor, the parameter field should look like:: + + (raw mode, stride, orientation) + +The fields are used as follows: + +**raw mode** + The pixel layout used in the file, and is used to properly convert data to + PIL’s internal layout. For a summary of the available formats, see the + table below. + +**stride** + The distance in bytes between two consecutive lines in the image. If 0, the + image is assumed to be packed (no padding between lines). If omitted, the + stride defaults to 0. + +**orientation** + + Whether the first line in the image is the top line on the screen (1), or + the bottom line (-1). If omitted, the orientation defaults to 1. + +The **raw mode** field is used to determine how the data should be unpacked to +match PIL’s internal pixel layout. PIL supports a large set of raw modes; for a +complete list, see the table in the :py:mod:`Unpack.c` module. The following +table describes some commonly used **raw modes**: + ++-----------+-----------------------------------------------------------------+ +| mode | description | ++===========+=================================================================+ +| ``1`` | 1-bit bilevel, stored with the leftmost pixel in the most | +| | significant bit. 0 means black, 1 means white. | ++-----------+-----------------------------------------------------------------+ +| ``1;I`` | 1-bit inverted bilevel, stored with the leftmost pixel in the | +| | most significant bit. 0 means white, 1 means black. | ++-----------+-----------------------------------------------------------------+ +| ``1;R`` | 1-bit reversed bilevel, stored with the leftmost pixel in the | +| | least significant bit. 0 means black, 1 means white. | ++-----------+-----------------------------------------------------------------+ +| ``L`` | 8-bit greyscale. 0 means black, 255 means white. | ++-----------+-----------------------------------------------------------------+ +| ``L;I`` | 8-bit inverted greyscale. 0 means white, 255 means black. | ++-----------+-----------------------------------------------------------------+ +| ``P`` | 8-bit palette-mapped image. | ++-----------+-----------------------------------------------------------------+ +| ``RGB`` | 24-bit true colour, stored as (red, green, blue). | ++-----------+-----------------------------------------------------------------+ +| ``BGR`` | 24-bit true colour, stored as (blue, green, red). | ++-----------+-----------------------------------------------------------------+ +| ``RGBX`` | 24-bit true colour, stored as (blue, green, red, pad). | ++-----------+-----------------------------------------------------------------+ +| ``RGB;L`` | 24-bit true colour, line interleaved (first all red pixels, the | +| | all green pixels, finally all blue pixels). | ++-----------+-----------------------------------------------------------------+ + +Note that for the most common cases, the raw mode is simply the same as the mode. + +The Python Imaging Library supports many other decoders, including JPEG, PNG, +and PackBits. For details, see the :file:`decode.c` source file, and the +standard plug-in implementations provided with the library. + +Decoding floating point data +---------------------------- + +PIL provides some special mechanisms to allow you to load a wide variety of +formats into a mode ``F`` (floating point) image memory. + +You can use the ``raw`` decoder to read images where data is packed in any +standard machine data type, using one of the following raw modes: + +============ ======================================= +mode description +============ ======================================= +``F`` 32-bit native floating point. +``F;8`` 8-bit unsigned integer. +``F;8S`` 8-bit signed integer. +``F;16`` 16-bit little endian unsigned integer. +``F;16S`` 16-bit little endian signed integer. +``F;16B`` 16-bit big endian unsigned integer. +``F;16BS`` 16-bit big endian signed integer. +``F;16N`` 16-bit native unsigned integer. +``F;16NS`` 16-bit native signed integer. +``F;32`` 32-bit little endian unsigned integer. +``F;32S`` 32-bit little endian signed integer. +``F;32B`` 32-bit big endian unsigned integer. +``F;32BS`` 32-bit big endian signed integer. +``F;32N`` 32-bit native unsigned integer. +``F;32NS`` 32-bit native signed integer. +``F;32F`` 32-bit little endian floating point. +``F;32BF`` 32-bit big endian floating point. +``F;32NF`` 32-bit native floating point. +``F;64F`` 64-bit little endian floating point. +``F;64BF`` 64-bit big endian floating point. +``F;64NF`` 64-bit native floating point. +============ ======================================= + +The bit decoder +--------------- + +If the raw decoder cannot handle your format, PIL also provides a special “bit” +decoder that can be used to read various packed formats into a floating point +image memory. + +To use the bit decoder with the fromstring function, use the following syntax:: + + image = fromstring( + mode, size, data, "bit", + bits, pad, fill, sign, orientation + ) + +When used in a tile descriptor, the parameter field should look like:: + + (bits, pad, fill, sign, orientation) + +The fields are used as follows: + +**bits** + Number of bits per pixel (2-32). No default. + +**pad** + Padding between lines, in bits. This is either 0 if there is no padding, or + 8 if lines are padded to full bytes. If omitted, the pad value defaults to + 8. + +**fill** + Controls how data are added to, and stored from, the decoder bit buffer. + +**fill=0** + Add bytes to the LSB end of the decoder buffer; store pixels from the MSB + end. + +**fill=1** + Add bytes to the MSB end of the decoder buffer; store pixels from the MSB + end. + +**fill=2** + Add bytes to the LSB end of the decoder buffer; store pixels from the LSB + end. + +**fill=3** + Add bytes to the MSB end of the decoder buffer; store pixels from the LSB + end. + + If omitted, the fill order defaults to 0. + +**sign** + If non-zero, bit fields are sign extended. If zero or omitted, bit fields + are unsigned. + +**orientation** + Whether the first line in the image is the top line on the screen (1), or + the bottom line (-1). If omitted, the orientation defaults to 1. diff --git a/docs/index.rst b/docs/index.rst index 89e89d4d5..883b1bdb3 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,18 +1,27 @@ -.. Pillow (PIL fork) documentation master file, created by - sphinx-quickstart on Fri Apr 12 19:51:26 2013. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. +Pillow: a modern fork of PIL +============================ -Welcome to Pillow (PIL fork)'s documentation! -============================================= +Pillow is the "friendly" PIL fork by Alex Clark and Contributors. PIL is the +Python Imaging Library by Fredrik Lundh and Contributors. -Contents: +Pillow >= 2.0.0 supports Python versions 2.6, 2.7, 3.2, 3.3. + +Pillow < 2.0.0 supports Python versions 2.4, 2.5, 2.6, 2.7. + +For general information including installation instructions, see `README.rst`_. +If you can't find the information you need, try the old `PIL Handbook`_, but be +aware that it was last updated for PIL 1.1.5. + +.. _README.rst: https://github.com/python-imaging/Pillow/blob/master/README.rst +.. _PIL Handbook: http://effbot.org/imagingbook/pil-index.htm .. toctree:: - :maxdepth: 4 + :maxdepth: 2 + handbook/guides.rst + handbook/appendices.rst PIL - + plugins Indices and tables ================== @@ -20,4 +29,3 @@ Indices and tables * :ref:`genindex` * :ref:`modindex` * :ref:`search` - diff --git a/docs/plugins.rst b/docs/plugins.rst new file mode 100644 index 000000000..b92b500c1 --- /dev/null +++ b/docs/plugins.rst @@ -0,0 +1,330 @@ +Plugin reference +================ + +:mod:`ArgImagePlugin` Module +---------------------------- + +.. automodule:: PIL.ArgImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`BmpImagePlugin` Module +---------------------------- + +.. automodule:: PIL.BmpImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`BufrStubImagePlugin` Module +--------------------------------- + +.. automodule:: PIL.BufrStubImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`CurImagePlugin` Module +---------------------------- + +.. automodule:: PIL.CurImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`DcxImagePlugin` Module +---------------------------- + +.. automodule:: PIL.DcxImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`EpsImagePlugin` Module +---------------------------- + +.. automodule:: PIL.EpsImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`FitsStubImagePlugin` Module +--------------------------------- + +.. automodule:: PIL.FitsStubImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`FliImagePlugin` Module +---------------------------- + +.. automodule:: PIL.FliImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`FpxImagePlugin` Module +---------------------------- + +.. automodule:: PIL.FpxImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`GbrImagePlugin` Module +---------------------------- + +.. automodule:: PIL.GbrImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`GifImagePlugin` Module +---------------------------- + +.. automodule:: PIL.GifImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`GribStubImagePlugin` Module +--------------------------------- + +.. automodule:: PIL.GribStubImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`Hdf5StubImagePlugin` Module +--------------------------------- + +.. automodule:: PIL.Hdf5StubImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`IcnsImagePlugin` Module +----------------------------- + +.. automodule:: PIL.IcnsImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`IcoImagePlugin` Module +---------------------------- + +.. automodule:: PIL.IcoImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`ImImagePlugin` Module +--------------------------- + +.. automodule:: PIL.ImImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`ImtImagePlugin` Module +---------------------------- + +.. automodule:: PIL.ImtImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`IptcImagePlugin` Module +----------------------------- + +.. automodule:: PIL.IptcImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`JpegImagePlugin` Module +----------------------------- + +.. automodule:: PIL.JpegImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`McIdasImagePlugin` Module +------------------------------- + +.. automodule:: PIL.McIdasImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`MicImagePlugin` Module +---------------------------- + +.. automodule:: PIL.MicImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`MpegImagePlugin` Module +----------------------------- + +.. automodule:: PIL.MpegImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`MspImagePlugin` Module +---------------------------- + +.. automodule:: PIL.MspImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`PalmImagePlugin` Module +----------------------------- + +.. automodule:: PIL.PalmImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`PcdImagePlugin` Module +---------------------------- + +.. automodule:: PIL.PcdImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`PcxImagePlugin` Module +---------------------------- + +.. automodule:: PIL.PcxImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`PdfImagePlugin` Module +---------------------------- + +.. automodule:: PIL.PdfImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`PixarImagePlugin` Module +------------------------------ + +.. automodule:: PIL.PixarImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`PngImagePlugin` Module +---------------------------- + +.. automodule:: PIL.PngImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`PpmImagePlugin` Module +---------------------------- + +.. automodule:: PIL.PpmImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`PsdImagePlugin` Module +---------------------------- + +.. automodule:: PIL.PsdImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`SgiImagePlugin` Module +---------------------------- + +.. automodule:: PIL.SgiImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`SpiderImagePlugin` Module +------------------------------- + +.. automodule:: PIL.SpiderImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`SunImagePlugin` Module +---------------------------- + +.. automodule:: PIL.SunImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`TgaImagePlugin` Module +---------------------------- + +.. automodule:: PIL.TgaImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`TiffImagePlugin` Module +----------------------------- + +.. automodule:: PIL.TiffImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`WebPImagePlugin` Module +----------------------------- + +.. automodule:: PIL.WebPImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`WmfImagePlugin` Module +---------------------------- + +.. automodule:: PIL.WmfImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`XVThumbImagePlugin` Module +-------------------------------- + +.. automodule:: PIL.XVThumbImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`XbmImagePlugin` Module +---------------------------- + +.. automodule:: PIL.XbmImagePlugin + :members: + :undoc-members: + :show-inheritance: + +:mod:`XpmImagePlugin` Module +---------------------------- + +.. automodule:: PIL.XpmImagePlugin + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/requirements.txt b/docs/requirements.txt new file mode 100644 index 000000000..af38b4b69 --- /dev/null +++ b/docs/requirements.txt @@ -0,0 +1,17 @@ +# requirements for working on docs + +# install pillow from master if you're into that, but RtD needs this +pillow>=2.2.0 + +Jinja2==2.7.1 +MarkupSafe==0.18 +Pygments==1.6 +Sphinx==1.1.3 +docopt==0.6.1 +docutils==0.11 +wsgiref==0.1.2 +sphinx-better-theme==0.1.5 + +# livereload not strictly necessary but really useful (make livehtml) +tornado==3.1.1 +livereload==1.0.1 diff --git a/libImaging/Convert.c b/libImaging/Convert.c index ab02910a7..2caf219ea 100644 --- a/libImaging/Convert.c +++ b/libImaging/Convert.c @@ -289,6 +289,31 @@ rgba2rgba(UINT8* out, const UINT8* in, int xsize) } } +/* RGBa -> RGBA conversion to remove premultiplication + Needed for correct transforms/resizing on RGBA images */ +static void +rgba2rgbA(UINT8* out, const UINT8* in, int xsize) +{ + int x; + unsigned int alpha; + for (x = 0; x < xsize; x++, in+=4) { + alpha = in[3]; + if (alpha) { + *out++ = CLIP((255 * in[0]) / alpha); + *out++ = CLIP((255 * in[1]) / alpha); + *out++ = CLIP((255 * in[2]) / alpha); + } else { + *out++ = in[0]; + *out++ = in[1]; + *out++ = in[2]; + } + *out++ = in[3]; + + } +} + + + /* ---------------- */ /* CMYK conversions */ /* ---------------- */ @@ -619,6 +644,8 @@ static struct { { "RGBA", "CMYK", rgb2cmyk }, { "RGBA", "YCbCr", ImagingConvertRGB2YCbCr }, + { "RGBa", "RGBA", rgba2rgbA }, + { "RGBX", "1", rgb2bit }, { "RGBX", "L", rgb2l }, { "RGBA", "I", rgb2i },