Skip to content

Commit 297965a

Browse files
committed
Added bit_depth attribute to PngImageFile
1 parent fe054a1 commit 297965a

3 files changed

Lines changed: 24 additions & 0 deletions

File tree

Tests/test_file_png.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,19 @@ def test_interlace(self) -> None:
222222

223223
im.load()
224224

225+
@pytest.mark.parametrize(
226+
"test_file, expected_bit_depth",
227+
(
228+
("Tests/images/hopper.png", 8),
229+
("Tests/images/hopper_bw_500.png", 1),
230+
("Tests/images/tiny.png", 4),
231+
("Tests/images/i_trns.png", 16),
232+
),
233+
)
234+
def test_bit_depth(self, test_file: str, expected_bit_depth: int) -> None:
235+
with Image.open(test_file) as im:
236+
assert im.bit_depth == expected_bit_depth
237+
225238
def test_load_transparent_p(self) -> None:
226239
test_file = "Tests/images/pil123p.png"
227240
with Image.open(test_file) as im:

docs/handbook/image-file-formats.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -895,6 +895,14 @@ decompression bombs. Additionally, the total size of all of the text
895895
chunks is limited to :data:`.PngImagePlugin.MAX_TEXT_MEMORY`, defaulting to
896896
64MB.
897897

898+
The :py:class:`~PIL.PngImagePlugin.PngImageFile` class also exposes the
899+
following attribute:
900+
901+
**bit_depth**
902+
The per-sample bit depth read from the PNG ``IHDR`` chunk. Valid values
903+
depend on the PNG color type and are one of ``1``, ``2``, ``4``, ``8`` or
904+
``16``.
905+
898906
.. _png-saving:
899907

900908
Saving

src/PIL/PngImagePlugin.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,7 @@ def __init__(self, fp: IO[bytes]) -> None:
391391
self.im_text: dict[str, str | iTXt] = {}
392392
self.im_size = (0, 0)
393393
self.im_mode = ""
394+
self.im_bit_depth = 0
394395
self.im_tile: list[ImageFile._Tile] = []
395396
self.im_palette: tuple[str, bytes] | None = None
396397
self.im_custom_mimetype: str | None = None
@@ -459,6 +460,7 @@ def chunk_IHDR(self, pos: int, length: int) -> bytes:
459460
msg = "Truncated IHDR chunk"
460461
raise ValueError(msg)
461462
self.im_size = i32(s, 0), i32(s, 4)
463+
self.im_bit_depth = s[8]
462464
try:
463465
self.im_mode, self.im_rawmode = _MODES[(s[8], s[9])]
464466
except Exception:
@@ -801,6 +803,7 @@ def _open(self) -> None:
801803
self._mode = self.png.im_mode
802804
self._size = self.png.im_size
803805
self.info = self.png.im_info
806+
self.bit_depth = self.png.im_bit_depth
804807
self._text: dict[str, str | iTXt] | None = None
805808
self.tile = self.png.im_tile
806809
self.custom_mimetype = self.png.im_custom_mimetype

0 commit comments

Comments
 (0)