40 lines
1.1 KiB
Python
40 lines
1.1 KiB
Python
import sys
|
|
|
|
from PIL import Image
|
|
|
|
def two_bpp_index(px):
|
|
indices = {0x00: 0, 0x55: 1, 0xaa: 2, 0xff: 3}
|
|
assert px in indices, px
|
|
return indices[px]
|
|
|
|
def convert(image):
|
|
assert image.mode == 'L', image.mode
|
|
width, height = image.size
|
|
|
|
buf = bytearray(width * height // 2)
|
|
|
|
for cell_y in range(height//8):
|
|
for cell_x in range(width//8):
|
|
for y in range(8):
|
|
for x in range(8):
|
|
px = im.getpixel((cell_x * 8 + x, cell_y * 8 + y))
|
|
index = two_bpp_index(px)
|
|
buf_ix = x//2 + (4 * (cell_x * 8 + (cell_y * width) + y))
|
|
buf[buf_ix] |= (index << 4 * (1 - (x % 2)))
|
|
return buf
|
|
|
|
def debug(buf):
|
|
for row in range(len(buf) // 4):
|
|
for x in range(4):
|
|
px = buf[row * 4 + x]
|
|
print((px >> 4) & 0xf, end='')
|
|
print((px >> 0) & 0xf, end='')
|
|
print()
|
|
if (row % 8 == 7):
|
|
print()
|
|
|
|
im = Image.open(sys.argv[1])
|
|
buf = convert(im)
|
|
with open(sys.argv[2], 'wb') as f:
|
|
f.write(buf)
|