imagepreview

package module
v1.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 28, 2026 License: BSD-3-Clause Imports: 31 Imported by: 1

README

imagepreview

A Go package for loading and previewing images in the terminal.

General info
  • Version: 1.2.3
  • License: BSD-3

Documentation

Index

Constants

View Source
const (
	// BlockRune is the UTF-8 block character used for text-based image rendering.
	BlockRune = '▒'

	// ASCIIRune is the ASCII fallback character used for text-based image rendering.
	ASCIIRune = '#'
)

Variables

View Source
var (
	// Sync is a global mutex to coordinate terminal output between text and graphics.
	Sync sync.Mutex

	// IsKitty is true when TERM=xterm-kitty, enabling Kitty graphics protocol features.
	IsKitty = env.Str("TERM") == "xterm-kitty"

	// IsITerm2 is true when running inside iTerm2 (which sets TERM_PROGRAM=iTerm.app).
	IsITerm2 = env.Str("TERM_PROGRAM") == "iTerm.app"

	// IsSixel is true when the terminal is known to support the Sixel graphics
	// protocol. Currently detected for foot, mlterm, yaft, contour, and wezterm.
	IsSixel = isSixelTerminal()

	// IsVT is true when TERM starts with vt100 or vt220.
	IsVT = strings.HasPrefix(env.Str("TERM"), "vt100") || strings.HasPrefix(env.Str("TERM"), "vt220")

	// HasGraphics is true when the terminal supports an inline image protocol.
	// It is disabled if TERM is vt100/vt220 or if NO_COLOR is set.
	HasGraphics = (IsKitty || IsITerm2 || IsSixel) && !IsVT && !env.Bool("NO_COLOR")

	// ImageExts lists file extensions handled by the image preview path.
	ImageExts = map[string]bool{
		".png": true, ".jpg": true, ".jpeg": true, ".gif": true,
		".svg": true, ".qoi": true, ".ico": true,
		".bmp": true, ".webp": true, ".tiff": true, ".tif": true,
	}

	// PaletteColorMap maps RGB values to VT100 attribute colors for fast lookup.
	PaletteColorMap map[[3]uint8]vt.AttributeColor
)

Functions

func AspectRatioCells

func AspectRatioCells(imgW, imgH, availCols, availRows uint) (cols, rows uint)

AspectRatioCells computes the display size in terminal cells that best fits the given image (imgW x imgH pixels) inside the available area (availCols x availRows cells) while preserving the image's pixel aspect ratio.

func BeginSync added in v1.0.9

func BeginSync()

BeginSync locks the global Sync mutex and emits the terminal's begin synchronized update escape sequence. Pair this with EndSync.

func ConvertToNRGBA

func ConvertToNRGBA(img image.Image) (*image.NRGBA, error)

ConvertToNRGBA converts the given image.Image to *image.NRGBA.

func ConvertToPNG

func ConvertToPNG(ctx context.Context, args ...string) (encoded string, w, h uint, err error)

ConvertToPNG runs an external command that writes PNG data to stdout, base64-encodes the result, and returns the encoded string with pixel dimensions.

func DeleteInlineImages

func DeleteInlineImages()

DeleteInlineImages sends the appropriate protocol command to delete all previously placed inline images. For Kitty it issues an explicit delete; iTerm2 and Sixel don't require one (overwriting the cells is sufficient).

func DeleteKittyImageByID added in v1.1.2

func DeleteKittyImageByID(id uint32)

DeleteKittyImageByID deletes a previously placed Kitty image by its ID. This is much cheaper than DeleteInlineImages which deletes ALL images.

func DrawOnCanvas

func DrawOnCanvas(canvas *vt.Canvas, m image.Image, drawRune rune) error

DrawOnCanvas draws the given image onto a VT100 Canvas using the basic 16-color palette. The drawRune parameter specifies the character used for each pixel (typically BlockRune or ASCIIRune).

func DrawTextImage

func DrawTextImage(canvas *vt.Canvas, path string, col, row, cols, rows uint, drawRune rune)

DrawTextImage renders an image file into a region of a VT100 Canvas using colored characters. col and row specify the top-left corner (0-indexed canvas coordinates); cols and rows specify the available area in terminal cells. The drawRune parameter specifies the character used for each pixel (typically BlockRune or ASCIIRune).

func EndSync added in v1.0.9

func EndSync()

EndSync emits the terminal's end synchronized update escape sequence and unlocks the global Sync mutex. Pair this with BeginSync.

func FlushImage

func FlushImage(w io.Writer, encoded string, dispCols, dispRows uint)

FlushImage writes an image to w using the appropriate terminal graphics protocol: Kitty (f=100 PNG), iTerm2 (inline image), or Sixel. For Kitty and iTerm2, encoded is base64-encoded PNG data. For Sixel, encoded is base64-encoded PNG data that will be decoded and re-encoded as Sixel. dispCols and dispRows specify the display size in terminal cells.

func FlushImageWithID added in v1.1.2

func FlushImageWithID(w io.Writer, encoded string, dispCols, dispRows uint, id uint32)

FlushImageWithID writes a base64-encoded PNG image to w using the Kitty graphics protocol with an explicit image ID, or the iTerm2 inline protocol (which ignores the ID). The image is transmitted and displayed immediately. For Sixel terminals, the ID is ignored (Sixel has no image ID concept).

func FlushRawRGBAWithID added in v1.2.2

func FlushRawRGBAWithID(w io.Writer, img *image.RGBA, dispCols, dispRows uint, id uint32)

FlushRawRGBAWithID writes an *image.RGBA to w using the Kitty graphics protocol with raw 32-bit RGBA pixel data (f=32) and zlib compression (o=z). This is significantly faster than PNG encoding because it skips PNG's per-scanline filter step. For non-Kitty terminals, falls back to PNG.

func FlushSixelImage added in v1.1.2

func FlushSixelImage(w io.Writer, img image.Image)

FlushSixelImage writes an image.Image directly as a Sixel sequence to w. This is more efficient than going through base64 PNG encoding when the caller already has the image in memory.

func IsImageExt

func IsImageExt(path string) bool

IsImageExt checks if the file extension indicates a supported image file.

func LoadImage

func LoadImage(filename string) (*image.NRGBA, error)

LoadImage loads an image and converts it to *image.NRGBA. PNG, JPEG, ICO, GIF, BMP, WebP, QOI and TIFF images are supported.

func ScaleNearestNeighbor

func ScaleNearestNeighbor(src image.Image, dstW, dstH int) *image.RGBA

ScaleNearestNeighbor scales src to dstW x dstH using nearest-neighbor interpolation, producing sharp pixels instead of a blurry bilinear upscale.

func SixelEncode added in v1.1.2

func SixelEncode(w io.Writer, img image.Image)

SixelEncode writes img to w as a Sixel escape sequence. The image is quantised to at most sixelMaxColors and rendered in bands of 6 pixel rows, which is how the Sixel protocol works.

func TerminalCellPixels

func TerminalCellPixels() (cellW, cellH uint)

TerminalCellPixels returns the terminal's cell dimensions in pixels by querying the kernel via TIOCGWINSZ. Falls back to (8, 16) when pixel info is unavailable or when the resulting aspect ratio is unrealistic.

func TestRenderWithoutColor added in v1.0.4

func TestRenderWithoutColor(t *testing.T)

Types

type PreviewResult

type PreviewResult struct {
	Path    string
	Encoded string // base64-encoded PNG
	ImgW    uint   // pixel width of the source image
	ImgH    uint   // pixel height of the source image
}

PreviewResult holds a fully-prepared image preview ready to be displayed. Encoded is always base64-encoded PNG data (Kitty format f=100).

func LoadAndEncode

func LoadAndEncode(ctx context.Context, path string, panePixW, panePixH uint) (PreviewResult, error)

LoadAndEncode decodes an image file, re-encodes it as PNG, and base64-encodes the result. The returned PreviewResult is ready to be passed to FlushImage.

PNG files are forwarded verbatim when they are large enough to not require upscaling. All other formats (JPEG, GIF, etc.) are decoded and re-encoded as PNG because the Kitty graphics protocol only supports raw pixel data and PNG (f=100). Small images are pre-scaled with nearest-neighbor so Kitty renders sharp pixels instead of a blurry bilinear upscale.

SVG files are rendered via native Go packages; JPEG XL files are converted via ImageMagick (magick).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL