Skip to content

Commit 065722b

Browse files
author
Matt Land
committed
optimize binary loads
1 parent 0269c39 commit 065722b

1 file changed

Lines changed: 7 additions & 12 deletions

File tree

adafruit_imageload/pnm/pgm/__init__.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,10 @@ def load(file, magic_number, header, *, bitmap=None, palette=None):
7979
return bitmap, palette
8080

8181
if magic_number == b"P5": # To handle binary PGM files.
82-
while True:
83-
byte = file.read(1)
84-
if byte == b"":
85-
break
86-
int_pixel = int.from_bytes(byte, "little")
87-
palette_colors.add(int_pixel)
82+
for y in range(height):
83+
data_line = iter(bytes(file.read(width)))
84+
for pixel in data_line:
85+
palette_colors.add(pixel)
8886

8987
if palette:
9088
palette = build_palette(palette, palette_colors)
@@ -93,12 +91,9 @@ def load(file, magic_number, header, *, bitmap=None, palette=None):
9391
palette_colors = list(palette_colors)
9492
file.seek(data_start)
9593
for y in range(height):
96-
for x in range(width):
97-
byte = file.read(1)
98-
if byte == b"":
99-
raise ValueError("ran out of file unexpectedly")
100-
int_pixel = int.from_bytes(byte, "little")
101-
bitmap[x, y] = palette_colors.index(int_pixel)
94+
data_line = iter(bytes(file.read(width)))
95+
for x, pixel in enumerate(data_line):
96+
bitmap[x, y] = palette_colors.index(pixel)
10297
return bitmap, palette
10398

10499
raise NotImplementedError("Was not able to send image")

0 commit comments

Comments
 (0)