Skip to content

Instantly share code, notes, and snippets.

@euhmeuh
Created May 3, 2017 15:59
Show Gist options
  • Save euhmeuh/07cbf1f2d198a72ed0194bbe479d856c to your computer and use it in GitHub Desktop.
Save euhmeuh/07cbf1f2d198a72ed0194bbe479d856c to your computer and use it in GitHub Desktop.
Generate a XBM image from an ASCII art string
def ascii_to_xbm(string, black='#', white=' '):
"""Generate a XBM image from an ascii art string"""
# purify input by removing all empty lines
# and all lines that contains illegal characters
lines = []
for line in string.split('\n'):
if not line:
continue
if not all([c in (black, white) for c in line]):
continue
lines.append(line)
width = len(max(lines, key=len))
height = len(lines)
# fill incomplete lines with spaces
lines = map(lambda l: l.ljust(width, white), lines)
lines = "".join(lines)
databytes = []
for chunk in chunks(lines, 8):
byte = 0x00
for i, char in enumerate(chunk, start=0):
if char == black:
byte += 2 ** i
databytes.append(format(byte, '#04x'))
result = """
#define im_width {0}
#define im_height {1}
static char im_bits[] = {{\n{2}\n}};
"""
return result.format(width, height, ",".join(databytes))
def chunks(string, size):
"""Cut a string in chunks of the given size"""
return [string[i:i + size] for i in range(0, len(string), size)]
pixels = """
################################
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# #
# ##### ##### #### ##### #
# # # # # #
# # ### ### # #
# # # # # #
# # ##### #### # #
# #
# #
# #
#
# #
# #
# #
# #
#
# #
# #
# #
# #
#################
"""
print(ascii_to_xbm(pixels))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment