-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathim2c
executable file
·71 lines (56 loc) · 1.91 KB
/
im2c
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
#!/bin/env python3
########################################################################
## PIC ADI Image 2 C Array Converter
##
## Author: Michael R. Shannon
##
## This program is meant to be called from the command line.
##
########################################################################
import sys
from PIL import Image
from bitarray import bitarray
def to_array(filename):
"""Load monochrome image into a bitarray."""
bit_array = bitarray(endian="little")
with Image.open(filename) as im:
pixels = im.load()
for i in range(0, im.size[0]):
for j in range(0, im.size[1]):
bit_array.append(pixels[i, j] != 0)
return bit_array.tobytes()
def chunks(array, length):
"""Turn array into iterable of given chunk length."""
chunk = [None]*length
idx = 0
for v in array:
chunk[idx] = v
idx = (idx + 1) % length
if idx == 0:
yield chunk
def print_array(array):
"""Print array as a C style uint8_t array of size OLED_SIZE."""
print("uint8_t frameBuffer[OLED_SIZE] = {")
for line in chunks(array, 8):
print((" " + " 0x{:02X},"*8).format(*line))
print("};")
def check_size(filename):
"""Make sure image given by <filename> is 128x64 pixels."""
with Image.open(filename) as im:
if im.size != (128, 64):
print("Expected image of 128x64, got {}x{}".format(*im.size))
return True
return False
def convert_image(filename):
"""Convert monochrome image given by <filename> and print C array."""
if check_size(filename):
return
byte_array = to_array(filename)
print_array(byte_array)
if __name__ == "__main__":
"""Handle parsing of filename from terminal argument and convert."""
try:
filename = sys.argv[1]
except IndexError:
print("{} expects at least one argument".format(sys.argv[0]))
convert_image(filename)