1
0
Fork 0

tools: rle_encode: Rework into proper functions

This commit is contained in:
Daniel Thompson 2020-01-23 22:01:57 +00:00
parent 8f231430b3
commit 4604603352

94
tools/rle_encode.py Normal file → Executable file
View file

@ -1,51 +1,67 @@
#!/usr/bin/env python3
import sys
from PIL import Image from PIL import Image
im = Image.open('pine64.png') def encode(im):
pixels = im.load() pixels = im.load()
rle = [] rle = []
rl = 0 rl = 0
px = 0 px = 0
for y in range(im.height):
for x in range(im.width):
newpx = pixels[x, y]
if newpx == px:
rl += 1
continue
assert(rl < 255)
rle.append(rl)
rl = 1
px = newpx
rle.append(rl)
sx = 240 for y in range(im.height):
sy = 240 for x in range(im.width):
image = bytes(rle) newpx = pixels[x, y]
if newpx == px:
if rl < 255:
rl += 1
else:
# Handle overflow
rle.append(255)
rle.append(0)
rl = 1
continue
# Start a new run
rle.append(rl)
rl = 1
px = newpx
# Handle the final run
rle.append(rl)
data = bytearray(2*sx) return (im.width, im.height, bytes(rle))
dp = 0
black = ord('#')
white = ord(' ')
color = black
for rl in image: def decode_to_ascii(image):
while rl: (sx, sy, rle) = image
data[dp] = color data = bytearray(2*sx)
data[dp+1] = color dp = 0
dp += 2 black = ord('#')
rl -= 1 white = ord(' ')
color = black
if dp >= (2*sx): for rl in rle:
print(data.decode('utf-8')) while rl:
dp = 0 data[dp] = color
data[dp+1] = color
dp += 2
rl -= 1
if color == black: if dp >= (2*sx):
color = white print(data.decode('utf-8'))
else: dp = 0
color = black
assert(dp == 0) if color == black:
color = white
else:
color = black
# Check the image is the correct length
assert(dp == 0)
image = encode(Image.open(sys.argv[1]))
# This is kinda cool for testing but let's leave this disabled until we add
# proper argument processing!
#decode_to_ascii(image)
print(f'# 1-bit RLE, generated from {sys.argv[1]}')
print(image) print(image)