This commit is contained in:
AJ Slater 2026-05-16 18:28:10 +10:00 committed by GitHub
commit bfdb95e3ef
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 25 additions and 0 deletions

View File

@ -222,6 +222,20 @@ class TestFilePng:
im.load()
@pytest.mark.parametrize(
"test_file, expected_bit_depth",
(
("Tests/images/hopper.png", 8),
("Tests/images/hopper_bw_500.png", 1),
("Tests/images/tiny.png", 4),
("Tests/images/i_trns.png", 16),
),
)
def test_bit_depth(self, test_file: str, expected_bit_depth: int) -> None:
with Image.open(test_file) as im:
assert isinstance(im, PngImagePlugin.PngImageFile)
assert im.bit_depth == expected_bit_depth
def test_load_transparent_p(self) -> None:
test_file = "Tests/images/pil123p.png"
with Image.open(test_file) as im:

View File

@ -895,6 +895,14 @@ decompression bombs. Additionally, the total size of all of the text
chunks is limited to :data:`.PngImagePlugin.MAX_TEXT_MEMORY`, defaulting to
64MB.
The :py:class:`~PIL.PngImagePlugin.PngImageFile` class also exposes the
following attribute:
**bit_depth**
The per-sample bit depth read from the PNG ``IHDR`` chunk. Valid values
depend on the PNG color type and are one of ``1``, ``2``, ``4``, ``8`` or
``16``.
.. _png-saving:
Saving

View File

@ -391,6 +391,7 @@ class PngStream(ChunkStream):
self.im_text: dict[str, str | iTXt] = {}
self.im_size = (0, 0)
self.im_mode = ""
self.im_bit_depth = 0
self.im_tile: list[ImageFile._Tile] = []
self.im_palette: tuple[str, bytes] | None = None
self.im_custom_mimetype: str | None = None
@ -459,6 +460,7 @@ class PngStream(ChunkStream):
msg = "Truncated IHDR chunk"
raise ValueError(msg)
self.im_size = i32(s, 0), i32(s, 4)
self.im_bit_depth = s[8]
try:
self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
except Exception:
@ -801,6 +803,7 @@ class PngImageFile(ImageFile.ImageFile):
self._mode = self.png.im_mode
self._size = self.png.im_size
self.info = self.png.im_info
self.bit_depth = self.png.im_bit_depth
self._text: dict[str, str | iTXt] | None = None
self.tile = self.png.im_tile
self.custom_mimetype = self.png.im_custom_mimetype