Added alpha_only argument to getbbox()

This commit is contained in:
Andrew Murray 2023-05-02 08:41:18 +10:00
parent 96bdbc4afe
commit 15ef533df9
2 changed files with 20 additions and 2 deletions

View File

@ -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

View File

@ -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):
"""