Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Tests/test_file_png.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,20 @@ def test_interlace(self) -> None:

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:
Expand Down
8 changes: 8 additions & 0 deletions docs/handbook/image-file-formats.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/PIL/PngImagePlugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,7 @@ def __init__(self, fp: IO[bytes]) -> None:
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
Expand Down Expand Up @@ -459,6 +460,7 @@ def chunk_IHDR(self, pos: int, length: int) -> bytes:
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:
Expand Down Expand Up @@ -801,6 +803,7 @@ def _open(self) -> None:
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
Expand Down
Loading