forked from adafruit/Adafruit_CircuitPython_ImageLoad
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpbm_binary.py
More file actions
76 lines (63 loc) · 1.84 KB
/
pbm_binary.py
File metadata and controls
76 lines (63 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# SPDX-FileCopyrightText: 2018 Scott Shawcroft for Adafruit Industries
# SPDX-FileCopyrightText: 2022-2023 Matt Land
# SPDX-FileCopyrightText: Brooke Storm
# SPDX-FileCopyrightText: Sam McGahan
#
# SPDX-License-Identifier: MIT
"""
`adafruit_imageload.pnm.pbm_binary`
====================================================
Load pixel values (indices or colors) into a bitmap and for an ascii ppm,
return None for pallet.
* Author(s): Matt Land, Brooke Storm, Sam McGahan
"""
try:
from io import BufferedReader
from typing import Iterator, Optional, Tuple
from displayio import Bitmap, Palette
except ImportError:
pass
__version__ = "0.0.0+auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_ImageLoad.git"
def load(
file: BufferedReader,
width: int,
height: int,
bitmap: Bitmap,
palette: Optional[Palette] = None,
) -> Tuple[Bitmap, Optional[Palette]]:
"""
Load a P4 'PBM' binary image into the Bitmap
"""
padded_width = (width + 7) // 8 * 8
x = 0
y = 0
while True:
next_byte = file.read(1)
if not next_byte:
break # out of bits
for bit in iterbits(next_byte):
if x < width:
bitmap[x, y] = bit
x += 1
if x > padded_width - 1:
y += 1
x = 0
if y > height - 1:
break
return bitmap, palette
def iterbits(b: bytes) -> Iterator[int]:
"""
generator to iterate over the bits in a byte (character)
"""
in_char = reverse(int.from_bytes(b, "little"))
for i in range(8):
yield (in_char >> i) & 1
def reverse(b: int) -> int:
"""
reverse bit order so the iterbits works
"""
b = (b & 0xF0) >> 4 | (b & 0x0F) << 4
b = (b & 0xCC) >> 2 | (b & 0x33) << 2
b = (b & 0xAA) >> 1 | (b & 0x55) << 1
return b