Python PIL.Image.core() Examples

The following are 30 code examples for showing how to use PIL.Image.core(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module PIL.Image , or try the search function .

Example 1
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 6 votes vote down vote up
def _getdecoder(mode, decoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        decoder = DECODERS[decoder_name]
    except KeyError:
        pass
    else:
        return decoder(mode, *args + extra)

    try:
        # get decoder
        decoder = getattr(core, decoder_name + "_decoder")
    except AttributeError:
        raise OSError("decoder %s not available" % decoder_name)
    return decoder(mode, *args + extra) 
Example 2
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 6 votes vote down vote up
def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
    except KeyError:
        pass
    else:
        return encoder(mode, *args + extra)

    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
    except AttributeError:
        raise OSError("encoder %s not available" % encoder_name)
    return encoder(mode, *args + extra)


# --------------------------------------------------------------------
# Simple expression analyzer 
Example 3
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 6 votes vote down vote up
def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1)) 
Example 4
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 6 votes vote down vote up
def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha)) 
Example 5
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 6 votes vote down vote up
def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
    except KeyError:
        pass
    else:
        return encoder(mode, *args + extra)

    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
    except AttributeError:
        raise OSError("encoder %s not available" % encoder_name)
    return encoder(mode, *args + extra)


# --------------------------------------------------------------------
# Simple expression analyzer 
Example 6
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 6 votes vote down vote up
def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1)) 
Example 7
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 6 votes vote down vote up
def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha)) 
Example 8
def handler(data, context):
    """Handle request.

    Args:
        data (obj): the request data
        context (Context): an object containing request and configuration details

    Returns:
        (bytes, string): data to return to client, (optional) response content type
    """

    # use the imported library
    print('pillow: {}\n{}'.format(PIL.__version__, dir(_imaging)))
    processed_input = _process_input(data, context)
    response = requests.post(context.rest_uri, data=processed_input)
    return _process_output(response, context) 
Example 9
Project: python3_ios   Author: holzschu   File: Image.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _getdecoder(mode, decoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        decoder = DECODERS[decoder_name]
        return decoder(mode, *args + extra)
    except KeyError:
        pass
    try:
        # get decoder
        decoder = getattr(core, decoder_name + "_decoder")
        return decoder(mode, *args + extra)
    except AttributeError:
        raise IOError("decoder %s not available" % decoder_name) 
Example 10
Project: python3_ios   Author: holzschu   File: Image.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
        return encoder(mode, *args + extra)
    except KeyError:
        pass
    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
        return encoder(mode, *args + extra)
    except AttributeError:
        raise IOError("encoder %s not available" % encoder_name)


# --------------------------------------------------------------------
# Simple expression analyzer 
Example 11
Project: python3_ios   Author: holzschu   File: Image.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1)) 
Example 12
Project: python3_ios   Author: holzschu   File: Image.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha)) 
Example 13
Project: python3_ios   Author: holzschu   File: test_file_eps.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_scale1(self):
        # We need png support for these render test
        codecs = dir(Image.core)
        if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
            self.skipTest("zip/deflate support not available")

        # Zero bounding box
        image1_scale1 = Image.open(file1)
        image1_scale1.load()
        image1_scale1_compare = Image.open(file1_compare).convert("RGB")
        image1_scale1_compare.load()
        self.assert_image_similar(image1_scale1, image1_scale1_compare, 5)

        # Non-Zero bounding box
        image2_scale1 = Image.open(file2)
        image2_scale1.load()
        image2_scale1_compare = Image.open(file2_compare).convert("RGB")
        image2_scale1_compare.load()
        self.assert_image_similar(image2_scale1, image2_scale1_compare, 10) 
Example 14
Project: python3_ios   Author: holzschu   File: test_file_eps.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_scale2(self):
        # We need png support for these render test
        codecs = dir(Image.core)
        if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
            self.skipTest("zip/deflate support not available")

        # Zero bounding box
        image1_scale2 = Image.open(file1)
        image1_scale2.load(scale=2)
        image1_scale2_compare = Image.open(file1_compare_scale2).convert("RGB")
        image1_scale2_compare.load()
        self.assert_image_similar(image1_scale2, image1_scale2_compare, 5)

        # Non-Zero bounding box
        image2_scale2 = Image.open(file2)
        image2_scale2.load(scale=2)
        image2_scale2_compare = Image.open(file2_compare_scale2).convert("RGB")
        image2_scale2_compare.load()
        self.assert_image_similar(image2_scale2, image2_scale2_compare, 10) 
Example 15
Project: python3_ios   Author: holzschu   File: test_tiff_ifdrational.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ifd_rational_save(self):
        methods = (True, False)
        if 'libtiff_encoder' not in dir(Image.core):
            methods = (False,)

        for libtiff in methods:
            TiffImagePlugin.WRITE_LIBTIFF = libtiff

            im = hopper()
            out = self.tempfile('temp.tiff')
            res = IFDRational(301, 1)
            im.save(out, dpi=(res, res), compression='raw')

            reloaded = Image.open(out)
            self.assertEqual(float(IFDRational(301, 1)),
                             float(reloaded.tag_v2[282])) 
Example 16
Project: python3_ios   Author: holzschu   File: test_file_wmf.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_load_raw(self):

        # Test basic EMF open and rendering
        im = Image.open('Tests/images/drawing.emf')
        if hasattr(Image.core, "drawwmf"):
            # Currently, support for WMF/EMF is Windows-only
            im.load()
            # Compare to reference rendering
            imref = Image.open('Tests/images/drawing_emf_ref.png')
            imref.load()
            self.assert_image_similar(im, imref, 0)

        # Test basic WMF open and rendering
        im = Image.open('Tests/images/drawing.wmf')
        if hasattr(Image.core, "drawwmf"):
            # Currently, support for WMF/EMF is Windows-only
            im.load()
            # Compare to reference rendering
            imref = Image.open('Tests/images/drawing_wmf_ref.png')
            imref.load()
            self.assert_image_similar(im, imref, 2.0) 
Example 17
Project: python3_ios   Author: holzschu   File: test_file_libtiff.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_gimp_tiff(self):
        # Read TIFF JPEG images from GIMP [@PIL168]

        codecs = dir(Image.core)
        if "jpeg_decoder" not in codecs:
            self.skipTest("jpeg support not available")

        filename = "Tests/images/pil168.tif"
        im = Image.open(filename)

        self.assertEqual(im.mode, "RGB")
        self.assertEqual(im.size, (256, 256))
        self.assertEqual(
            im.tile, [('jpeg', (0, 0, 256, 256), 0, ('RGB', 'jpeg', False))]
        )
        im.load()

        self.assert_image_equal_tofile(im, "Tests/images/pil168.png") 
Example 18
Project: python3_ios   Author: holzschu   File: test_image_split.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_split_open(self):
        codecs = dir(Image.core)

        if 'zip_encoder' in codecs:
            test_file = self.tempfile("temp.png")
        else:
            test_file = self.tempfile("temp.pcx")

        def split_open(mode):
            hopper(mode).save(test_file)
            im = Image.open(test_file)
            return len(im.split())
        self.assertEqual(split_open("1"), 1)
        self.assertEqual(split_open("L"), 1)
        self.assertEqual(split_open("P"), 1)
        self.assertEqual(split_open("RGB"), 3)
        if 'zip_encoder' in codecs:
            self.assertEqual(split_open("RGBA"), 4) 
Example 19
Project: python3_ios   Author: holzschu   File: test_file_png.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_leak_load(self):
        with open('Tests/images/hopper.png', 'rb') as f:
            DATA = BytesIO(f.read(16 * 1024))

        ImageFile.LOAD_TRUNCATED_IMAGES = True
        with Image.open(DATA) as im:
            im.load()

        def core():
            with Image.open(DATA) as im:
                im.load()

        try:
            self._test_leak(core)
        finally:
            ImageFile.LOAD_TRUNCATED_IMAGES = False 
Example 20
Project: FODI   Author: vcheckzen   File: Image.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _getdecoder(mode, decoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        decoder = DECODERS[decoder_name]
    except KeyError:
        pass
    else:
        return decoder(mode, *args + extra)

    try:
        # get decoder
        decoder = getattr(core, decoder_name + "_decoder")
    except AttributeError:
        raise OSError("decoder %s not available" % decoder_name)
    return decoder(mode, *args + extra) 
Example 21
Project: FODI   Author: vcheckzen   File: Image.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
    except KeyError:
        pass
    else:
        return encoder(mode, *args + extra)

    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
    except AttributeError:
        raise OSError("encoder %s not available" % encoder_name)
    return encoder(mode, *args + extra)


# --------------------------------------------------------------------
# Simple expression analyzer 
Example 22
Project: FODI   Author: vcheckzen   File: Image.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1)) 
Example 23
Project: FODI   Author: vcheckzen   File: Image.py    License: GNU General Public License v3.0 6 votes vote down vote up
def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha)) 
Example 24
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 5 votes vote down vote up
def close(self):
        """
        Closes the file pointer, if possible.

        This operation will destroy the image core and release its memory.
        The image data will be unusable afterward.

        This function is only required to close images that have not
        had their file read and closed by the
        :py:meth:`~PIL.Image.Image.load` method. See
        :ref:`file-handling` for more information.
        """
        try:
            if hasattr(self, "_close__fp"):
                self._close__fp()
            self.fp.close()
            self.fp = None
        except Exception as msg:
            logger.debug("Error closing: %s", msg)

        if getattr(self, "map", None):
            self.map = None

        # Instead of simply setting to None, we're setting up a
        # deferred error that will better explain that the core image
        # object is gone.
        self.im = deferred_error(ValueError("Operation on closed image")) 
Example 25
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 5 votes vote down vote up
def __setstate__(self, state):
        Image.__init__(self)
        self.tile = []
        info, mode, size, palette, data = state
        self.info = info
        self.mode = mode
        self._size = size
        self.im = core.new(mode, size)
        if mode in ("L", "LA", "P", "PA") and palette:
            self.putpalette(palette)
        self.frombytes(data) 
Example 26
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 5 votes vote down vote up
def _wedge():
    """Create greyscale wedge (for debugging only)"""

    return Image()._new(core.wedge("L")) 
Example 27
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 5 votes vote down vote up
def new(mode, size, color=0):
    """
    Creates a new image with the given mode and size.

    :param mode: The mode to use for the new image. See:
       :ref:`concept-modes`.
    :param size: A 2-tuple, containing (width, height) in pixels.
    :param color: What color to use for the image.  Default is black.
       If given, this should be a single integer or floating point value
       for single-band modes, and a tuple for multi-band modes (one value
       per band).  When creating RGB images, you can also use color
       strings as supported by the ImageColor module.  If the color is
       None, the image is not initialised.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    _check_size(size)

    if color is None:
        # don't initialize
        return Image()._new(core.new(mode, size))

    if isinstance(color, str):
        # css3-style specifier

        from . import ImageColor

        color = ImageColor.getcolor(color, mode)

    im = Image()
    if mode == "P" and isinstance(color, (list, tuple)) and len(color) in [3, 4]:
        # RGB or RGBA value for a P image
        from . import ImagePalette

        im.palette = ImagePalette.ImagePalette()
        color = im.palette.getcolor(color)
    return im._new(core.fill(mode, size, color)) 
Example 28
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 5 votes vote down vote up
def alpha_composite(im1, im2):
    """
    Alpha composite im2 over im1.

    :param im1: The first image. Must have mode RGBA.
    :param im2: The second image.  Must have mode RGBA, and the same size as
       the first image.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.alpha_composite(im1.im, im2.im)) 
Example 29
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 5 votes vote down vote up
def effect_mandelbrot(size, extent, quality):
    """
    Generate a Mandelbrot set covering the given extent.

    :param size: The requested size in pixels, as a 2-tuple:
       (width, height).
    :param extent: The extent to cover, as a 4-tuple:
       (x0, y0, x1, y2).
    :param quality: Quality.
    """
    return Image()._new(core.effect_mandelbrot(size, extent, quality)) 
Example 30
Project: teleport   Author: tp4a   File: Image.py    License: Apache License 2.0 5 votes vote down vote up
def effect_noise(size, sigma):
    """
    Generate Gaussian noise centered around 128.

    :param size: The requested size in pixels, as a 2-tuple:
       (width, height).
    :param sigma: Standard deviation of noise.
    """
    return Image()._new(core.effect_noise(size, sigma))