Skip to content

Instantly share code, notes, and snippets.

@andrepiske
Last active February 9, 2026 13:13
Show Gist options
  • Select an option

  • Save andrepiske/6b3532ed06204c914aa1fda26a09906f to your computer and use it in GitHub Desktop.

Select an option

Save andrepiske/6b3532ed06204c914aa1fda26a09906f to your computer and use it in GitHub Desktop.
term_print_png.rb
# it's possible to print pictures in terminal. iTerm2 works with the usualy image formats, but isn't as powerful as kitty's protocol.
# here's iTerm2 docs: https://iterm2.com/documentation-escape-codes.html
#
# Kitty term documents the "Terminal graphics protocol", here:
# https://sw.kovidgoyal.net/kitty/graphics-protocol/
# It supports only PNG files directly. For other formats, one has to produce the raw pixel byte data and print that (not in this gist).
# But it is more powerful in the ways in can display and store the images (this gist just displays it using the most simple method).
#
require 'base64'
img_data = File.read('picture.png', encoding: 'ascii-8bit')
enc_data = Base64.strict_encode64(img_data).b
# iTerm2
if ENV['LC_TERMINAL'] == 'iTerm2'
print("\x1B]1337;File=inline=1;size=#{img_data.length}:#{enc_data}\x07")
# Kitty graphics protocol (tested in Kitty and Ghostty)
else
offset = 0
cs = 4032
num_chunks = (enc_data.length / cs.to_f).ceil
(0...num_chunks).each do |chunk_no|
limit = [offset + cs, enc_data.length].min
data = enc_data[offset...limit]
offset += cs
last_chunk = (chunk_no == num_chunks - 1)
metadata = (chunk_no == 0 ? "a=T,f=100," : '')
print("\x1B_G#{metadata}m=#{last_chunk ? 0 : 1};#{data}\x1B\\")
end
end
puts ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment