Skip to content

Commit f4d93b2

Browse files
author
Steve Canny
committed
img: add _ChunkParser._iter_chunk_offsets()
1 parent 67fab7e commit f4d93b2

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

docx/image/png.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,16 @@ def _iter_chunk_offsets(self):
253253
in the PNG image stream. Iteration stops after the IEND chunk is
254254
returned.
255255
"""
256-
raise NotImplementedError
256+
chunk_offset = 8
257+
while True:
258+
chunk_data_len = self._stream_rdr.read_long(chunk_offset)
259+
chunk_type = self._stream_rdr.read_str(4, chunk_offset, 4)
260+
data_offset = chunk_offset + 8
261+
yield chunk_type, data_offset
262+
if chunk_type == 'IEND':
263+
break
264+
# incr offset for chunk len long, chunk type, chunk data, and CRC
265+
chunk_offset += (4 + 4 + chunk_data_len + 4)
257266

258267

259268
def _ChunkFactory(chunk_type, stream_rdr, offset):

tests/image/test_png.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -355,6 +355,12 @@ def it_can_iterate_over_the_chunks_in_its_png_stream(self, iter_fixture):
355355
]
356356
assert chunks == chunk_lst
357357

358+
def it_iterates_over_the_chunk_offsets_to_help_parse(
359+
self, iter_offsets_fixture):
360+
chunk_parser, expected_chunk_offsets = iter_offsets_fixture
361+
chunk_offsets = [co for co in chunk_parser._iter_chunk_offsets()]
362+
assert chunk_offsets == expected_chunk_offsets
363+
358364
# fixtures -------------------------------------------------------
359365

360366
@pytest.fixture
@@ -408,6 +414,17 @@ def iter_fixture(
408414
offsets, chunk_lst
409415
)
410416

417+
@pytest.fixture
418+
def iter_offsets_fixture(self):
419+
bytes_ = b'-filler-\x00\x00\x00\x00IHDRxxxx\x00\x00\x00\x00IEND'
420+
stream_rdr = StreamReader(BytesIO(bytes_), BIG_ENDIAN)
421+
chunk_parser = _ChunkParser(stream_rdr)
422+
expected_chunk_offsets = [
423+
(PNG_CHUNK_TYPE.IHDR, 16),
424+
(PNG_CHUNK_TYPE.IEND, 28),
425+
]
426+
return chunk_parser, expected_chunk_offsets
427+
411428
@pytest.fixture
412429
def StreamReader_(self, request, stream_rdr_):
413430
return class_mock(

0 commit comments

Comments
 (0)