1
0
Fork 0
stm32/anim/sprite.py

124 lines
3.3 KiB
Python
Executable File

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
# 128x64
# convert gnaa.png +dither -monochrome -colors 2 image.bmp
from PIL import Image
import argparse
import sys
import math
import zlib
#import zlib
invert = 0
def set_bit(value, bit):
return value | (1<<bit)
def clear_bit(value, bit):
return value & ~(1<<bit)
def print_array(name, buf, bytes_per_line = 15):
c = 0
print("uint8_t " + name + "[" + str(len(buf)) + "] = {")
for v in buf:
if c == 0:
print(" ", end='')
if c > 0 and c < bytes_per_line:
print(' ', end='')
print(format(v, '#04x') + ",", end='')
c = c + 1
if (c == bytes_per_line):
print()
c = 0
if (c <= bytes_per_line):
print()
print("};")
print()
if __name__ == "__main__":
#if (len(sys.argv) < 2):
# sys.exit()
parser = argparse.ArgumentParser(description='Convert images to the SSD1306 display.')
parser.add_argument("--files", nargs="*", type=str,
help="List of files to convert",
default=None)
parser.add_argument("--header", help="Print header instead of source", action='store_true')
args = parser.parse_args()
frames = []
counter = 0
for file in args.files:
im = Image.open(file)
width, height = im.size
if (height > 64 or width > 128):
sys.exit()
banks = math.ceil(height / 8);
buf = []
for bank in range(0, banks):
for x in range(0, width):
value = 0
if (invert == 1):
value = 255
c = 7
for y in range( (bank * 8 ) + 7, (bank * 8) - 1, -1):
#print(bank, x, y)
b = im.getpixel((x,y))
if (b == 1 or b == 255):
value = set_bit(value, c)
if (invert == 1):
value = clear_bit(value, c)
c = c - 1
buf.append(value)
frames.append({'name': 'frame' + str(counter), 'buf': zlib.compress(bytes(buf))})
counter = counter + 1
if args.header:
print('#include "stm32f4xx_hal.h"')
print()
print('typedef struct {')
print(' uint8_t width;')
print(' uint8_t height;')
print(' uint8_t *buffer;')
print('} SpriteDef;')
print()
print('typedef struct {')
print(' uint8_t width;')
print(' uint8_t height;')
print(' uint8_t frames;')
print(' uint8_t *buffer[' + str(len(frames)) + '];')
print('} AnimationDef;')
print()
print('extern AnimationDef animation;')
else:
print('#include "sprites.h"')
print()
for item in frames:
print_array(item['name'] + "_data", item['buf'])
print('AnimationDef animation = {')
print(' .width = ' + str(width) + ',')
print(' .height = ' + str(height) + ',')
print(' .frames = ' + str(len(frames)) + ',')
print(' .buffer = {')
for item in frames:
print(' ' + item['name'] + '_data,')
print(' }')
print('};')