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

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

@ -1,36 +1,46 @@
#!/usr/bin/env python3
import sys
from PIL import Image
im = Image.open('pine64.png')
pixels = im.load()
def encode(im):
pixels = im.load()
rle = []
rl = 0
px = 0
rle = []
rl = 0
px = 0
for y in range(im.height):
for y in range(im.height):
for x in range(im.width):
newpx = pixels[x, y]
if newpx == px:
if rl < 255:
rl += 1
else:
# Handle overflow
rle.append(255)
rle.append(0)
rl = 1
continue
assert(rl < 255)
# Start a new run
rle.append(rl)
rl = 1
px = newpx
rle.append(rl)
# Handle the final run
rle.append(rl)
sx = 240
sy = 240
image = bytes(rle)
return (im.width, im.height, bytes(rle))
def decode_to_ascii(image):
(sx, sy, rle) = image
data = bytearray(2*sx)
dp = 0
black = ord('#')
white = ord(' ')
color = black
data = bytearray(2*sx)
dp = 0
black = ord('#')
white = ord(' ')
color = black
for rl in image:
for rl in rle:
while rl:
data[dp] = color
data[dp+1] = color
@ -46,6 +56,12 @@ for rl in image:
else:
color = black
assert(dp == 0)
# 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)