Skip to content

Commit 17866e3

Browse files
author
Steve Canny
committed
img: add Png.horz_dpi
1 parent 73132ba commit 17866e3

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

docx/image/png.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,22 @@ def from_stream(cls, stream, blob, filename):
3939
cx, cy = attrs.pop('px_width'), attrs.pop('px_height')
4040
return Png(blob, filename, cx, cy, attrs)
4141

42+
@property
43+
def horz_dpi(self):
44+
"""
45+
Integer dots per inch for the width of this image. Defaults to 72
46+
when not present in the file, as is often the case.
47+
"""
48+
units_specifier = self._attrs.get(TAG.UNITS_SPECIFIER)
49+
horz_px_per_unit = self._attrs.get(TAG.HORZ_PX_PER_UNIT)
50+
51+
if units_specifier == 1 and horz_px_per_unit is not None:
52+
horz_dpi = int(round(horz_px_per_unit * 0.0254))
53+
else:
54+
horz_dpi = 72
55+
56+
return horz_dpi
57+
4258
@classmethod
4359
def _parse_png_headers(cls, stream):
4460
"""

features/img-characterize-image.feature

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ Feature: Characterize an image file
1515

1616
Examples: Image file characteristics
1717
| filename | mime_type | cx | cy | horz_dpi | vert_dpi |
18-
| test.png | image/png | 901 | 1350 | 333 | 444 |
18+
| test.png | image/png | 901 | 1350 | 150 | 444 |

tests/image/test_png.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,10 @@ def it_can_parse_an_pHYs_chunk(self, parse_pHYs_fixture):
7171
attrs = Png._parse_pHYs(stream, offset)
7272
assert attrs == expected_attrs
7373

74+
def it_knows_its_horizontal_dpi(self, horz_dpi_fixture):
75+
png, expected_horz_dpi = horz_dpi_fixture
76+
assert png.horz_dpi == expected_horz_dpi
77+
7478
# fixtures -------------------------------------------------------
7579

7680
@pytest.fixture
@@ -120,6 +124,19 @@ def from_stream_fixture(
120124
stream_rdr_, Png__init__, cx, cy, attrs, png_
121125
)
122126

127+
@pytest.fixture(params=[
128+
(5906, 1, 150), (11811, 1, 300), (5906, 0, 72), (None, 0, 72),
129+
(666, 0, 72), (2835, 1, 72)
130+
])
131+
def horz_dpi_fixture(self, request):
132+
horz_px_per_unit, units_specifier, expected_horz_dpi = request.param
133+
attrs = {
134+
TAG.HORZ_PX_PER_UNIT: horz_px_per_unit,
135+
TAG.UNITS_SPECIFIER: units_specifier
136+
}
137+
png = Png(None, None, None, None, attrs)
138+
return png, expected_horz_dpi
139+
123140
@pytest.fixture
124141
def no_IHDR_fixture(self, stream_, chunk_offsets):
125142
return stream_, chunk_offsets

0 commit comments

Comments
 (0)