From 15ef533df9847e556eca0eaa50b7738bb71b8c34 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Tue, 2 May 2023 08:41:18 +1000 Subject: [PATCH] Added alpha_only argument to getbbox() --- Tests/test_image_getbbox.py | 15 +++++++++++++++ src/PIL/Image.py | 7 +++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Tests/test_image_getbbox.py b/Tests/test_image_getbbox.py index af69ed57a60..eec97821098 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 check(im, fill_color): 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 bee9e23d088..f5d1206717d 100644 --- a/src/PIL/Image.py +++ b/src/PIL/Image.py @@ -1279,11 +1279,14 @@ def getbands(self): """ 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 @@ def getbbox(self): """ self.load() - return self.im.getbbox() + return self.im.getbbox(alpha_only) def getcolors(self, maxcolors=256): """