Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nomissbowling/c005ffa3c3be4ea02b2888c4d667d7ce to your computer and use it in GitHub Desktop.
Save nomissbowling/c005ffa3c3be4ea02b2888c4d667d7ce to your computer and use it in GitHub Desktop.
interpolation_and_convert_png_to_ppm.py
SRC_BASE = f'{BASE}/misc'
SRC_BITMAP_8x8 = f'{SRC_BASE}/bmp_hex_136x8.png'
SRC_BITMAP_16x16 = f'{SRC_BASE}/bmp_hex_256x256_16x16.png'
PPM_BASE = f'{BASE}/textures'
PPM_TEXTURE_8x8 = f'{PPM_BASE}/custom_%c.ppm'
PPM_TEXTURE_16x16 = f'{PPM_BASE}/ascii_%02X.ppm'
cols = [
(0xff, 0x00, 0xff),
(0xff, 0x00, 0x00),
(0xee, 0xbb, 0x22),
(0xff, 0xff, 0x00),
(0x88, 0xee, 0x22),
(0x00, 0xff, 0x00),
(0x00, 0xff, 0xff),
(0x00, 0x00, 0xff)]
def interpol(s, e, a):
o = np.array(s)
d = np.array(e) - o
return (d * (a / 255.0) + o).astype(np.uint8)
def test_img(fn):
Image.open(fn).convert('RGB').show()
def create_p6_texture_8x8(k, a=None):
with open(PPM_TEXTURE_8x8 % k, 'wb') as ppm:
ppm.write(b'P6\n8 8\n255\n')
if k == 'R': # custom_R (horizontal)
for c in cols: ppm.write(bytes(c) * 8)
elif k == 'L': # custom_L (vertical)
for r in range(8):
for c in cols: ppm.write(bytes(c))
elif '0' <= k <= '9' or 'A' <= k <= 'F' or k == 'P': # custom_* (hex dot)
if '0' <= k <= '9': o = ord(k) - ord('0')
if 'A' <= k <= 'F': o = ord(k) - ord('A') + 10
if k == 'P': o = 16
for r in range(8):
for c in range(8):
ppm.write(bytes(cols[7] if a[r][o * 8 + (c + 4) % 8] else cols[2]))
else: # dummy
for c in cols: ppm.write(bytes(c) * 8)
def write_p6_texture_8x8():
create_p6_texture_8x8('R')
create_p6_texture_8x8('L')
im = Image.open(SRC_BITMAP_8x8).convert('L')
a = np.asarray(im, dtype=np.uint8) # rows:8 cols:136
for i in range(16): create_p6_texture_8x8('%X' % i, a)
create_p6_texture_8x8('P', a)
test_img(PPM_TEXTURE_8x8 % '4')
def create_p6_texture_16x16(k, a, b):
with open(PPM_TEXTURE_16x16 % k, 'wb') as ppm:
ppm.write(b'P6\n16 16\n255\n')
f = 0 <= k <= 0x1f or k == 0x7f
o = k % 16
p = k // 16
for r in range(16):
for c in range(16):
d = (b if f else a)[p * 16 + r][o * 16 + c]
m = (255 - d) if f else d[3]
ppm.write(bytes(interpol(cols[7], cols[2], m) if m else cols[7]))
def write_p6_texture_16x16():
im = Image.open(SRC_BITMAP_16x16)
a = np.asarray(im, dtype=np.uint8) # rows:16 cols:16 'RGBA'
b = np.asarray(im.convert('L'), dtype=np.uint8) # rows:16 cols:16 'L'
for i in range(128): create_p6_texture_16x16(i, a, b)
test_c = [
0x00, 0x12, 0x14, 0x1f, # @ R T _ (reversed)
0x20, 0x24, 0x30, 0x34, # (SPC) $ 0 4
0x40, 0x52, 0x54, 0x5f, # @ R T _
0x60, 0x6f, 0x72, 0x74, # ` o r t
0x7b, 0x7c, 0x7d, 0x7e, # { | } ~
0x7f] # (DEL) (reversed)
for c in test_c: test_img(PPM_TEXTURE_16x16 % c)
if __name__ == '__main__':
write_p6_texture_8x8()
write_p6_texture_16x16()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment