This repository has been archived by the owner on Oct 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpng2hex.py
79 lines (65 loc) · 2.28 KB
/
png2hex.py
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
77
78
79
#!/bin/python
import sys
from PIL import Image
colors = {
( 0, 0, 0): '0',
( 0, 0, 170): '1',
( 0, 170, 0): '2',
( 0, 170, 170): '3',
(170, 0, 0): '4',
(170, 0, 170): '5',
(170, 85, 0): '6',
(170, 170, 170): '7',
( 85, 85, 85): '8',
( 85, 85, 255): '9',
( 85, 255, 85): 'a',
( 85, 255, 255): 'b',
(255, 85, 85): 'c',
(255, 85, 255): 'd',
(255, 255, 85): 'e',
(255, 255, 255): 'f'
}
def png2hex(filename):
with Image.open(filename) as img:
(width, height) = img.size
print("Image is", width, "x", height, "pixels.")
print("Make sure image is not too large before using it, ", end="")
print("please check the README.md.\n")
bytes = []
first_px_pair = 0
# Loop over image pixels
for y in range(height):
for x in range(width):
# Get pixel color
px = img.getpixel((x, y))
# Ignore alpha value
(r, g, b, _) = px
px = (r, g, b)
# Check color is part of BIOS colors list
if px not in colors:
print(f"{px} at ({x}, {y}) is not allowed!")
print(f"Color must be in: {colors.keys()}")
return
# Pixels are encoded over 4 bits, so we can set 2 px / bytes.
# We check if we have a 2nd pixel to build a byte.
is_odd_px = (y * width + x) % 2
if is_odd_px:
# Build byte with two pixels value
bytes.append("0x" +
colors.get(px) +
colors.get(first_px_pair))
else:
# Store px for later byte build
first_px_pair = px
# If there are an odd number of pixels
if width * height % 2:
# Add the last pixel in a byte
bytes.append("0x0" + colors.get(first_px_pair))
# Print bytecode
print("Bytecode of the image, to use in .asm file: ")
print(','.join(bytes))
if __name__ == "__main__":
if len(sys.argv) != 2:
print(f"usage: {sys.argv[0]} path/to/image.png")
sys.exit(1)
png2hex(sys.argv[1])