Skip to content

Commit 845f402

Browse files
authored
Merge pull request #100 from carlossless/binary-pbm-width-fix
fix padded pbm binary loading
2 parents b9eb566 + 23f7866 commit 845f402

File tree

4 files changed

+31
-3
lines changed

4 files changed

+31
-3
lines changed

adafruit_imageload/pnm/pbm_binary.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,16 +38,18 @@ def load(
3838
"""
3939
Load a P4 'PBM' binary image into the Bitmap
4040
"""
41+
padded_width = (width + 7) // 8 * 8
4142
x = 0
4243
y = 0
4344
while True:
4445
next_byte = file.read(1)
4546
if not next_byte:
4647
break # out of bits
4748
for bit in iterbits(next_byte):
48-
bitmap[x, y] = bit
49+
if x < width:
50+
bitmap[x, y] = bit
4951
x += 1
50-
if x > width - 1:
52+
if x > padded_width - 1:
5153
y += 1
5254
x = 0
5355
if y > height - 1:
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
P4
2+
14 20
3+
�̷���������������{x|��g�C��{x�����
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# SPDX-FileCopyrightText: 2025 Karolis Stasaitis
2+
# SPDX-License-Identifier: MIT

tests/test_pbm_load.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def test_load_works_p1_ascii(self):
7272
palette.validate()
7373

7474
def test_load_works_p4_in_mem(self):
75-
file = BytesIO(b"P4\n4 2\n\x55")
75+
file = BytesIO(b"P4\n4 2\n\x5f\x5f")
7676
bitmap, palette = pnm.load(
7777
file, b"P4", bitmap=Bitmap_C_Interface, palette=Palette_C_Interface
7878
)
@@ -103,6 +103,27 @@ def test_load_works_p4_binary(self):
103103
self.assertEqual(15, bitmap.height)
104104
bitmap.validate()
105105

106+
def test_load_works_p4_binary_padded_width(self):
107+
test_file = os.path.join(
108+
os.path.dirname(__file__),
109+
"..",
110+
"examples",
111+
"images",
112+
"netpbm_p4_mono_width.pbm",
113+
)
114+
with open(test_file, "rb") as file:
115+
bitmap, palette = pnm.load(
116+
file, b"P4", bitmap=Bitmap_C_Interface, palette=Palette_C_Interface
117+
)
118+
self.assertEqual(1, palette.num_colors)
119+
palette.validate()
120+
self.assertEqual(b"\xff\xff\xff", palette[0])
121+
self.assertTrue(isinstance(bitmap, Bitmap_C_Interface))
122+
self.assertEqual(1, bitmap.colors)
123+
self.assertEqual(14, bitmap.width)
124+
self.assertEqual(20, bitmap.height)
125+
bitmap.validate()
126+
106127
def test_load_works_p4_binary_high_res(self):
107128
test_file = os.path.join(
108129
os.path.dirname(__file__),

0 commit comments

Comments
 (0)