Skip to content

Instantly share code, notes, and snippets.

@hatkidchan
Created January 27, 2023 08:33
Show Gist options
  • Save hatkidchan/59712e3eb907305ce328036dd152c347 to your computer and use it in GitHub Desktop.
Save hatkidchan/59712e3eb907305ce328036dd152c347 to your computer and use it in GitHub Desktop.
# x-run: python3 % /home/hkc/images/casey/photo_2022-09-20_19-34-19.jpg 64 64 | sh -
from zlib import compress
from PIL import Image
from sys import argv
from shlex import quote
TEMPLATE = (
"import zlib;"
'print("".join(['
"chr(x+(10<<10)) for x in zlib.decompress(%r.encode('U16')[2::2])"
']).replace("⣾⣭","\\n"))'
)
OFFSETS = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (0, 3), (1, 3)]
def main(path: str, width: int = 32, height: int = 32):
with Image.open(path) as im:
im.thumbnail((width * 2, height * 4))
img = im.convert("1", dither=1)
stream = bytearray()
for cy in range(img.height // 4):
for cx in range(im.width // 2):
byte: int = 0
for i, (ox, oy) in enumerate(OFFSETS):
byte |= bool(img.getpixel((cx * 2 + ox, cy * 4 + oy))) << i
stream.append(byte)
stream.extend(b"\xFE\xED")
braille = str.join("", [chr(0x2800 | c) for c in compress(stream, 9)])
print("python3 -c " + quote(TEMPLATE % braille))
if __name__ == "__main__":
main(argv[1], *map(int, argv[2:]))
# x-run: python3 % /home/hkc/images/casey/photo_2022-09-20_19-34-19.jpg 64 64
(lambda zlib,Image,sys:
(lambda img,_w="32",_h="32":
(img.thumbnail((int(_w)*2,int(_h)*4)),
(lambda im,tmpl:
(print(tmpl%str.join("",(chr(0x2800|c)for c in zlib.compress(bytes([
(
b"\xFE\xED"[x-im.width//2] if x >= im.width//2 else
sum([
bool(im.getpixel((x*2+ox,y*4+oy)))<<i
for i,(ox,oy)in enumerate([(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(0,3),(1,3)])
])&0xFF
)
for y in range(im.height//4)
for x in range(im.width//2+2)
])))))
)
)(img.convert("1",dither=1),"python3 -c 'import zlib;print(\"\".join([chr(x+(10<<10)) for x in zlib.decompress(\"%s\".encode(\"U16\")[2::2])]).replace(\"⣾⣭\",\"\\n\"))'"))
)(Image.Image.open(sys.argv[1]),*sys.argv[2:])
)(**{m.split(".")[-1]:__import__(m)for m in("zlib","PIL.Image","sys")})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment