/dev/posts/

Simple terminal image display using the iTerm2 image protocol

Published:

Updated:

A simple way to display image in a terminal using the iTerm2 image protocol. This is supported by iTerm2, WezTerm, recent versions of Konsole.

Shell

It is very simple to display an image using the iTerm2 protocol without any dedicated program:

(printf "\e]1337;File=inline=1:" ; base64 -w0 image.jpg  ; printf "\a\n")

Some alternatives:

References:

Matplotlib

Adding support for iTerm2 to Matplotlib can be done with:

# mpliterm.py
from matplotlib.backend_bases import Gcf
from matplotlib.backends.backend_agg import FigureCanvasAgg
from io import BytesIO
from base64 import b64encode
import sys

FigureCanvas = FigureCanvasAgg


def show(*args, **kwargs):
    for figmanager in Gcf.get_all_fig_managers():
        buffer = BytesIO()
        figmanager.canvas.figure.savefig(buffer, format="png")
        data = buffer.getvalue()
        data64 = b64encode(data).decode("ascii")
        sys.stdout.write('\x1b]1337;File=inline=1:' + data64 + "\a\n")

Used with:

export PYTHONPATH=/path-to-mplitem/
export MPLBACKEND=module://mpliterm
python3 test-plot.py
# test-plot.py
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 300)
y = np.cos(x)
plt.plot(x, y)
plt.show()

References: