Skip to content

Instantly share code, notes, and snippets.

@Mufanc
Last active June 15, 2025 18:04
Show Gist options
  • Save Mufanc/41bd73dcac88195c4818c46ccd8eb9d9 to your computer and use it in GitHub Desktop.
Save Mufanc/41bd73dcac88195c4818c46ccd8eb9d9 to your computer and use it in GitHub Desktop.
import math
import sys
import array
import fcntl
import termios
from base64 import b64encode
from PIL import Image
def cell_size():
buffer = array.array('H', [0, 0, 0, 0])
fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, buffer)
return int(buffer[2] / buffer[1]), int(buffer[3] / buffer[0])
def encode(data: bytes, **opts):
buffer = []
w = buffer.append
w(b'\033_G')
w(','.join(f'{k}={v}' for k, v in opts.items()).encode())
if data:
w(b';')
w(b64encode(data))
w(b'\033\\')
return b''.join(buffer)
def print_image(path: str, **kwargs):
image = Image.open(path)
cw, ch = cell_size()
iw, ih = image.size
screen_w = ch * iw / ih
offset_x = round((math.ceil(screen_w / cw) * cw - screen_w) / 2)
data = open(path, 'rb').read()
sys.stdout.flush()
while data:
chunk, data = data[:4096], data[4096:]
m = 1 if data else 0
sys.stdout.buffer.write(encode(chunk, a='T', f=100, r=1, X=offset_x, m=m, **kwargs))
sys.stdout.flush()
kwargs.clear()
if __name__ == '__main__':
print('ABC', end='')
print_image(sys.argv[1])
print('ABC')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment