gbprinter/twobpp.py

44 lines
1.3 KiB
Python

# twobpp.py - functions for the gameboy 2bpp graphics format and gameboy camera
from PIL import Image
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l), n):
yield l[i:i + n]
def decode_tile(tile):
"""Decodes an 8x8 2bpp gameboy tile, returns a 2d list containing the data"""
d = []
for i in range(0,16,2):
d.append(decode_line(tile[i], tile[i+1]))
return d
def decode_line(b1, b2):
"""Decodes an 8-pixel line of 2bpp gameboy graphics from two bytes"""
line = []
for i in range(8):
hi_bit = (b2 >> (7-i)) & 1;
lo_bit = (b1 >> (7-i)) & 1;
line.append((hi_bit << 1) | lo_bit)
return line
def convert_photo(byte_seq, colors, tiles_per_line, width, height):
"""converts the sequence of bytes from a gameboy camera image into a pillow image."""
tiles = [decode_tile(l) for l in byte_seq]
tile_image = []
for t in chunks(tiles, tiles_per_line):
chunk = []
for l in range(8):
line = []
for tile in range(tiles_per_line):
line += t[tile][l]
chunk += line
tile_image += chunk
image_data = [colors[x] for x in tile_image]
image = Image.new(mode='RGB',size=(width,height))
image.putdata(image_data)
return image