Skip to content

Commit a20f25b

Browse files
author
Steve Canny
committed
img: add Png._parse_pHYs()
1 parent 3042292 commit a20f25b

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

docx/image/helpers.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,15 @@ def __init__(self, stream, byte_order, base_offset=0):
2525
)
2626
self._base_offset = base_offset
2727

28+
def read_byte(self, base=None, offset=0):
29+
"""
30+
Return the int value of the byte at the file position defined by
31+
self._base_offset + *base* + *offset*. If *base* is None, the byte is
32+
read from the current position in the stream.
33+
"""
34+
fmt = 'B'
35+
return self._read_int(fmt, base, offset)
36+
2837
def read_long(self, base=None, offset=0):
2938
"""
3039
Return the int value of the four bytes at the file position defined by

docx/image/png.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,8 @@ def _parse_pHYs(cls, stream, offset):
111111
TAG.VERT_PX_PER_UNIT, and TAG.UNITS_SPECIFIER parsed from the pHYs
112112
chunk at *offset* in *stream*.
113113
"""
114-
raise NotImplementedError
114+
return {
115+
TAG.HORZ_PX_PER_UNIT: stream.read_long(offset),
116+
TAG.VERT_PX_PER_UNIT: stream.read_long(offset, 4),
117+
TAG.UNITS_SPECIFIER: stream.read_byte(offset, 8)
118+
}

tests/image/test_png.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ def it_can_parse_an_IHDR_chunk(self, parse_IHDR_fixture):
6666
attrs = Png._parse_IHDR(stream, offset)
6767
assert attrs == expected_attrs
6868

69+
def it_can_parse_an_pHYs_chunk(self, parse_pHYs_fixture):
70+
stream, offset, expected_attrs = parse_pHYs_fixture
71+
attrs = Png._parse_pHYs(stream, offset)
72+
assert attrs == expected_attrs
73+
6974
# fixtures -------------------------------------------------------
7075

7176
@pytest.fixture
@@ -142,6 +147,18 @@ def parse_IHDR_fixture(self):
142147
expected_attrs = {TAG.PX_WIDTH: 42, TAG.PX_HEIGHT: 24}
143148
return stream_rdr, offset, expected_attrs
144149

150+
@pytest.fixture
151+
def parse_pHYs_fixture(self):
152+
bytes_ = b'\x00\x00\x17\x12\x00\x00\x1E\xC2\x01'
153+
stream = BytesIO(bytes_)
154+
stream_rdr = StreamReader(stream, BIG_ENDIAN)
155+
offset = 0
156+
expected_attrs = {
157+
TAG.HORZ_PX_PER_UNIT: 5906, TAG.VERT_PX_PER_UNIT: 7874,
158+
TAG.UNITS_SPECIFIER: 1
159+
}
160+
return stream_rdr, offset, expected_attrs
161+
145162
@pytest.fixture
146163
def parse_png_fixture(
147164
self, stream_rdr_, _parse_chunk_offsets_, _parse_chunks_,

0 commit comments

Comments
 (0)