Skip to content

Commit

Permalink
Added alpha_only argument to getbbox()
Browse files Browse the repository at this point in the history
  • Loading branch information
radarhere committed May 1, 2023
1 parent 96bdbc4 commit 15ef533
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
15 changes: 15 additions & 0 deletions Tests/test_image_getbbox.py
@@ -1,3 +1,5 @@
import pytest

from PIL import Image

from .helper import hopper
Expand Down Expand Up @@ -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
7 changes: 5 additions & 2 deletions src/PIL/Image.py
Expand Up @@ -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
Expand All @@ -1292,7 +1295,7 @@ def getbbox(self):
"""

self.load()
return self.im.getbbox()
return self.im.getbbox(alpha_only)

def getcolors(self, maxcolors=256):
"""
Expand Down

0 comments on commit 15ef533

Please sign in to comment.