diff --git a/Tests/test_image_getbbox.py b/Tests/test_image_getbbox.py index af69ed57a..eec978210 100644 --- a/Tests/test_image_getbbox.py +++ b/Tests/test_image_getbbox.py @@ -1,3 +1,5 @@ +import pytest + from PIL import Image from .helper import hopper @@ -38,3 +40,16 @@ def test_bbox(): for color in ((0, 0), (127, 0), (255, 0)): im = Image.new(mode, (100, 100), color) check(im, (255, 255)) + + +@pytest.mark.parametrize("mode", ("RGBA", "RGBa", "La", "LA", "PA")) +def test_bbox_alpha_only_false(mode): + im = Image.new(mode, (100, 100)) + assert im.getbbox(False) is None + + fill_color = [1] * Image.getmodebands(mode) + fill_color[-1] = 0 + im.paste(tuple(fill_color), (25, 25, 75, 75)) + assert im.getbbox(False) == (25, 25, 75, 75) + + assert im.getbbox() is None diff --git a/src/PIL/Image.py b/src/PIL/Image.py index bee9e23d0..f5d120671 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1279,11 +1279,14 @@ class Image: """ return ImageMode.getmode(self.mode).bands - def getbbox(self): + def getbbox(self, alpha_only=True): """ Calculates the bounding box of the non-zero regions in the image. + :param alpha_only: Optional flag, defaulting to true. + If true and the image has an alpha channel, trim transparent pixels. + Otherwise, trim pixels when all channels are zero. :returns: The bounding box is returned as a 4-tuple defining the left, upper, right, and lower pixel coordinate. See :ref:`coordinate-system`. If the image is completely empty, this @@ -1292,7 +1295,7 @@ class Image: """ self.load() - return self.im.getbbox() + return self.im.getbbox(alpha_only) def getcolors(self, maxcolors=256): """