tmux requires unrecognized OSC sequences to be wrapped with DCS tmux;
ST, and for all ESCs in to be replaced with ESC ESC. It
only accepts ESC backslash for . We use TERM instead of TMUX because TERM
gets passed through ssh.
function print_osc() {
if [[ TERM==screen∗∣∣TERM == tmux* ]]; then
printf "\033Ptmux;\033\033]"
else
printf "\033]"
fi
}
More of the tmux workaround described above.
function print_st() {
if [[ TTERM == tmux* ]]; then
printf "\a\033\"
else
printf "\a"
fi
}
Assistant
E
R
M
==
screen∗
∣∣
function load_version() {
if [ -z IMGCATBASE64VERSION+x];thenIMGCATBASE64VERSION=(base64 --version 2>&1)
export IMGCAT_BASE64_VERSION
fi
}
function b64_encode() {
load_version
if [[ $IMGCAT_BASE64_VERSION =~ GNU ]]; then
# Disable line wrap
base64 -w0
else
base64
fi
}
function b64_decode() {
load_version
if [[ IMGCATBASE64VERSION=fourmilab]];thenBASE64ARG=−delif[[IMGCAT_BASE64_VERSION =~ GNU ]]; then
BASE64ARG=-di
else
BASE64ARG=-D
fi
base64 $BASE64ARG
}
# Split into 200-byte chunks. This helps it get through tmux.
parts=$(printf "%s" "$3" | fold -w 200)
# Send each part.
for part in $parts; do
print_osc
printf '1337;FilePart=%s' "$part"
print_st
done
# Indicate completion
print_osc
printf '1337;FileEnd'
print_st
fi
printf '\n'
[ "$4" == "1" ] && echo "$1"
has_image_displayed=t
}
function error() {
errcho "ERROR: $*"
}
function errcho() {
echo "$@" >&2
}
function show_help() {
errcho
errcho "Usage: imgcat [-p] [-n] [-W width] [-H height] [-r] [-s] [-u] [-t file-type] [-f] filename ..."
errcho " cat filename | imgcat [-W width] [-H height] [-r] [-s]"
errcho
errcho "Display images inline in the iTerm2 using Inline Images Protocol"
errcho
errcho "Options:"
errcho
errcho " -h, --help Display help message"
errcho " -p, --print Enable printing of filename or URL after each image"
errcho " -n, --no-print Disable printing of filename or URL after each image"
errcho " -u, --url Interpret following filename arguments as remote URLs"
errcho " -f, --file Interpret following filename arguments as regular Files"
errcho " -t, --type file-type Provides a type hint"
errcho " -r, --preserve-aspect-ratio When scaling image preserve its original aspect ratio"
errcho " -s, --stretch Stretch image to specified width and height (this option is opposite to -r)"
errcho " -W, --width N Set image width to N character cells, pixels or percent (see below)"
errcho " -H, --height N Set image height to N character cells, pixels or percent (see below)"
errcho " -l, --legacy Use legacy protocol that sends the whole image in a single control sequence"
errcho
errcho " If you don't specify width or height an appropriate value will be chosen automatically."
errcho " The width and height are given as word 'auto' or number N followed by a unit:"
errcho " N character cells"
errcho " Npx pixels"
errcho " N% percent of the session's width or height"
errcho " auto the image's inherent size will be used to determine an appropriate dimension"
errcho
errcho " If a type is provided, it is used as a hint to disambiguate."
errcho " The file type can be a mime type like text/markdown, a language name like Java, or a file extension like .c"
errcho " The file type can usually be inferred from the extension or its contents. -t is most useful when"
errcho " a filename is not available, such as whe input comes from a pipe."
errcho
errcho "Examples:"
errcho
errcho " imgcat−W250px−H250px−savatar.png"errcho" cat graph.png | imgcat -W 100%"
errcho " imgcat−p−W500px− cat url_list.txt | xargs imgcat -p -W 40 -u"
errcho " $ imgcat -t application/json config.json"
errcho
}
function check_dependency() {
if ! (builtin command -V "1" >/dev/null 2>&1); then
error "missing dependency: can't find 1"
exit 1
fi
}
verify that value is in the image sizing unit format: N / Npx / N% / auto
function validate_size_unit() {
if [[ ! "1"=(:?[0−9]+(:?px∣ ]]; then
error "Invalid image sizing unit - '$1'"
show_help
exit 1
fi
}
Main
if [ -t 0 ]; then
has_stdin=f
else
has_stdin=t
fi
Show help if no arguments and no stdin.
if [ has_stdin = f ] && [ # -eq 0 ]; then
show_help
exit
fi
if [ hasstdin=t];thenprintimage""1"(cat | b64_encode)" 0 "width""height" "preserveaspectratio""file_type" "$legacy"
fi
if [ "$has_image_displayed" != "t" ]; then
error "No image provided. Check command line options."
show_help
exit 1
fi
exit 0Port this to Python as a Python function I can call with a filepath to an image
Here’s a self-contained Python port of yourimgcatlogic. You can drop this into a module (e.g.imgcat.py) and callimgcat("path/to/image.png", ...)to display inline images in (or inside tmux, screen, etc.):
pythonCopy codeimport os
import sys
import base64
import textwrap
def _print_osc():
term = os.environ.get("TERM", "")
if term.startswith("screen") or term.startswith("tmux"):
# wrap DCS for tmux/screen
sys.stdout.write("\033Ptmux;\033\033]")
else:
sys.stdout.write("\033]")
def _print_st():
term = os.environ.get("TERM", "")
if term.startswith("screen") or term.startswith("tmux"):
sys.stdout.write("\a\033\")
else:
sys.stdout.write("\a")
def imgcat(
filepath,
inline=True,
print_filename=False,
width=None,
height=None,
preserve_aspect_ratio=None,
file_type=None,
legacy=False
):
"""
Display an image inline via the iTerm2 Inline Images Protocol.
Args:
filepath (str): path to the image file.
inline (bool): if True, display inline; if False, force download.
print_filename (bool): if True, echo the filename after display.
width (str): e.g. "100px", "50%", "auto", or None.
height (str): same format as width or None.
preserve_aspect_ratio (bool or None): True => preserve (param=1), False => stretch (param=0), None => omit.
file_type (str or None): MIME, extension or language hint (e.g. "image/png" or ".js").
legacy (bool): if True, send one big control sequence; else chunk into 200-byte parts for tmux compatibility.
"""
# Read and base64-encode the file
with open(filepath, "rb") as f:
raw = ad()
f.read()
= base64.b64encode(raw).decode("ascii")
size = len(raw)
# Begin metadata sequence
_print_osc()
sys.stdout.write("1337;")
sys.stdout.write("File" if inline else "MultipartFile")
sys.stdout.write(f"=inline={1 if inline else 0}")
sys.stdout.write(f";size={size}")
if filepath:
name_enc = <REDACTED>()
sys.stdout.write(f";name={name_enc}")
if width:
sys.stdout.write(f";width={width}")
if height:
sys.stdout.write(f";height={height}")
if preserve_aspect_ratio is True:
sys.stdout.write(";preserveAspectRatio=1")
elif preserve_aspect_ratio is False:
sys.stdout.write(";preserveAspectRatio=0")
if file_type:
sys.stdout.write(f";type={file_type}")
if inline or legacy:
# one-shot
sys.stdout.write(f":{b64}")
_print_st()
else:
# multipart
_print_st()
for chunk in textwrap.wrap(b64, 200):
_print_osc()
sys.stdout.write(f"1337;FilePart={chunk}")
_print_st()
# end marker
_print_osc()
sys.stdout.write("1337;FileEnd")
_print_st()
sys.stdout.write("\n")
if print_filename:
sys.stdout.write(f"{filepath}\n")