Skip to content

Instantly share code, notes, and snippets.

@andreiavram
Last active February 26, 2017 16:42
Show Gist options
  • Save andreiavram/3fa75c3c5eab09472ab14faeeca20c0d to your computer and use it in GitHub Desktop.
Save andreiavram/3fa75c3c5eab09472ab14faeeca20c0d to your computer and use it in GitHub Desktop.
This script will convert an XBM file (X11 format) to a format compatible with the DigisparkOLED library
import re
import sys
assert len(sys.argv) >= 2, "Usage ./xbm_converter.py filename.xbm [invert] > image.h"
XBM_FILE = sys.argv[1]
INVERT = sys.argv[2] == "invert" if len(sys.argv) > 2 else False
WIDTH = 128
HEIGHT = 64
with open(XBM_FILE) as f:
data = f.read()
img_data = "".join(re.findall("0x([\da-f]{2})", data, re.MULTILINE))
img_bytes = bytearray.fromhex(img_data)
reordered_bytes = bytearray(WIDTH * HEIGHT / 8)
orig_img_binary_data = "".join("{0:08b}".format(int(i))[::-1] for i in img_bytes)
img_data_to_process = orig_img_binary_data
if INVERT:
orig_img_binary_data_inverted = "".join(map(lambda x: "0" if x == "1" else "1", orig_img_binary_data))
img_data_to_process = orig_img_binary_data_inverted
img_binary_data = list("".join("{0:08b}".format(i) for i in reordered_bytes))
for j, b in enumerate(img_data_to_process):
offset = WIDTH * 8 * (j / (WIDTH * 8))
i = j - offset
img_binary_data[offset + (i % WIDTH) * 8 + (i / WIDTH)] = b
reordered_bytes = [img_binary_data[i:i+8] for i in range(0, HEIGHT * WIDTH, 8)]
reordered_data = [hex(int("".join(i)[::-1], 2)) for i in reordered_bytes]
print "const uint8_t PROGMEM img[] = {"
for i in range(0, HEIGHT * WIDTH / 8, WIDTH / 8):
print ", ".join(reordered_data[i:i+WIDTH/8]), ", "
print "};"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment