#!/bin/python3 import itertools import io from PIL import Image, ImageDraw from consts import * from shared import main palette_img = Image.new('P', (1, 1)) palette_img.putpalette(list(itertools.chain.from_iterable([ *PICTOCHAT_PALETTE, *[PICTOCHAT_PALETTE[0] for x in range(256 - len(PICTOCHAT_PALETTE))], ]))) def convert_chunk(img, offset): palette_indices = [] for y in range(DS_TILE_SIZE): for x in range(DS_TILE_SIZE): palette_indices.append(img.getpixel((x + offset[0], y + offset[1]))) bytes = bytearray() for i in range(0, len(palette_indices), 2): bytes.append((palette_indices[i+0] << 0) | (palette_indices[i+1] << 4)) return bytes def png2pc(data): img = Image.open(io.BytesIO(data)) if img.width != TILES_HORIZONTAL * DS_TILE_SIZE: print(f"error: input image is not {TILES_HORIZONTAL * DS_TILE_SIZE} pixels wide") exit(1) if img.height % DS_TILE_SIZE != 0: print(f"error: input image height not a muliple of {DS_TILE_SIZE}") exit(1) tile_count = (img.width * img.height) // (DS_TILE_SIZE ** 2) img = img.convert('RGB') img = img.quantize(palette=palette_img) draw = ImageDraw.Draw(img) draw.rectangle(((0, 0), (23, img.height - 1)), fill=0) draw.rectangle(((252, 0), (255, img.height - 1)), fill=0) draw.rectangle(((24, 0), (78, 15)), fill=0) output = b"" for tile_idx in range(tile_count): tile = ( tile_idx % TILES_HORIZONTAL, tile_idx // TILES_HORIZONTAL, ) offset = ( tile[0] * DS_TILE_SIZE, tile[1] * DS_TILE_SIZE, ) output += convert_chunk(img, offset) return output if __name__ == "__main__": main("png", "bin", png2pc)