All 42 libraries

SugarImage

Image-to-cell renderer

inspired by charmbracelet/x/mosaic image sixel kitty iterm2 ext-gd chafa symbols

SugarImage code coverage

Image-to-cell renderer for the terminal. PNG, JPEG, GIF (still and animated), APNG, WebP and BMP decoded via ext-gd plus pure-PHP animated-container decoders and rendered via the best available protocol: Sixel, Kitty graphics, iTerm2 inline images, the chafa CLI — or one of the Unicode text tiers: half-block, quarter-block, an ASCII character ramp, or chafa's coverage-class symbol engine.

Install

composer require sugarcraft/sugar-image

Quickstart

use SugarCraft\Image\Mosaic;
use SugarCraft\Image\ImageSource;

$mosaic = Mosaic::halfBlock();
$image  = ImageSource::fromFile('examples/fixture-gradient.png');
$ansi   = $mosaic->render($image, width: 40, height: 20);
echo $ansi;

API

use SugarCraft\Image\ImageSource;
use SugarCraft\Image\Mosaic;
use SugarCraft\Image\Renderer\AsciiColorMode;
use SugarCraft\Image\Renderer\QuarterBlockRenderer;

$image  = ImageSource::fromFile('examples/fixture-gradient.png');

// Probe terminal once, pick best protocol
$mosaic = Mosaic::probe();

// Force a specific backend
$mosaic = Mosaic::sixel();
$mosaic = Mosaic::kitty();
$mosaic = Mosaic::iterm2();
$mosaic = Mosaic::halfBlock();
$mosaic = Mosaic::quarterBlock();
$mosaic = Mosaic::ascii();                          // character ramp, monochrome
$mosaic = Mosaic::ascii(AsciiColorMode::Ansi256);   // ...or Ansi16 / TrueColor chars
$mosaic = Mosaic::symbols();      // chafa symbol engine, default 676-glyph corpus
$mosaic = Mosaic::chafa('--colors=256');  // external chafa CLI (opt-in)

// Render — returns ANSI bytes
$ansi = $mosaic->render($image, width: 40, height: 20);

// Builder for fine-grained control; withResize() sets the default cell box
// render() uses when called without a width
$mosaic = Mosaic::builder()
    ->withRenderer(new QuarterBlockRenderer())
    ->withResize(width: 40, height: 20)
    ->build();
$ansi = $mosaic->render($image);          // 40×20 cells
$ansi = $mosaic->render($image, 60);      // explicit width wins; height from aspect

What's in the box

Sixel rendererxterm, foot, mlterm, contour support; mlterm and foot are recognized from TERM alone.
Kitty graphics protocolkitty, ghostty, wezterm support.
iTerm2 inline imagesOSC 1337 support for iTerm2 and mintty.
Unicode half-blockFallback for sighted readers on any Unicode-capable terminal using ▀ + 24-bit fg/bg, where the terminal honors cell geometry; the auto() floor of the fallback ladder is the symbol-map tier.
Unicode quarter-blockHigher fidelity using ░▒▓█ 2×2 sub-pixel rendering, again where cell geometry is honored (an explicit choice — not an auto() rung).
ext-gd integrationPNG, JPEG, static GIF via GD (imagecreatefrompng, imagecreatefromjpeg, imagecreatefromgif). ImageSource::fromString() also accepts anything imagecreatefromstring() decodes (WebP, BMP, …) with its real MIME in format; the Kitty/iTerm2 renderers re-encode any payload that is not PNG by signature. Animated GIF and APNG load via ImageSource::fromAnimatedFile(), which returns an Animation (frames + per-frame delays) to feed AnimationDriver. Pixel allocations are bounded before GD is asked for them.
Protocol detectionMosaic::probe() checks environment variables and the DA1 capability query on every call; Detect::cached() memoizes the answer per-process.
Kitty virtual-image placementStore once with KittyOptions::transmit(id)->withUseVirtual(true) (a=T,U=1 payload plus a trailing control-only a=p placement), then reference it at many offsets with KittyOptions::place(id, x:, y:) — a one-shot control-only a=p frame that never carries payload again.
Kitty zlib compressionCompress the PNG payload with zlib before base64-encoding via KittyOptions::withCompression(1) — emitted as f=100,o=z (compression rides the spec's o key). Useful for large images on slow links.
Half-block transparencyTransparent pixels (alpha=127) emit no SGR codes — terminal default background shows through. Enables overlay compositing on existing terminal content.
Sixel 256-color fallbackPass maxColors (1–256) to SixelRenderer constructor to limit palette size for terminals with limited truecolor support. It is a constructor knob, so it rides the builder: Mosaic::builder()->withRenderer(new SixelRenderer(maxColors: 64))->build(). Mosaic::sixel(dither, intensity) exposes the dither axis plus intensity (0.0–1.0 Ordered/Noise bias; null keeps the chafa default 1.0).
Symbol-map engine (chafa parity)Unicode braille/sextant/octant/block glyph cells chosen by Hamming-distance candidate search — pure inline SGR that reaches any Unicode terminal; glyph fidelity depends on the font's coverage (restrict the corpus via symbols:), making it the practical universal floor of the ladder. Mosaic::symbols(canvas:, workFactor:, symbols:) selects the color canvas, candidate budget, and chafa's --symbols= tag grammar over the 1,251-glyph effective corpus (1,260 parsed, nine AMBIGUOUS-tagged misc-narrow glyphs BAD-vetoed even by all); the default 676-glyph corpus is byte-frozen. A double-width wide-glyph engine carries the opt-in kana tier.
ASCII character rampMosaic::ascii() maps one luminance sample per cell onto a character ramp; AsciiColorMode::Ansi16 | Ansi256 | TrueColor carries pixel colors on the characters themselves.
chafa CLI tierChafaRenderer shells out to the chafa command with option passthrough — output is bounded and the child is reaped on a TERM→KILL ladder. Binary discovery is gated (InfocmpBinary precedent): a fixed absolute roster or the explicit SUGAR_IMAGE_CHAFA override, never an implicit PATH search for the program that produces image output. Opt-in only; the pure-PHP tiers never shell out for pixel data. The only other spawns are the two tmux capability consults and the stty terminal-state round-trip: the tmux consults pass argv arrays with no shell between; the stty save and arm are constant strings and only the restore interpolates, escapeshellarg-quoted — reached only inside an existing session, and never feed rendered bytes.
Remote imagesImageSource::fromUrl() / fromUrlAsync() (ReactPHP) with a security floor: scheme allowlist re-checked every redirect hop, and any host resolving to a private/loopback/link-local/reserved address (including cloud metadata) is refused. Disclosed residuals (authority: the README Security note): the host check runs at guard time, not connect time — a TTL-0 DNS-rebinding TOCTOU is undefended, so proxy the fetch if you need a connect-time guarantee — and on the async path the byte ceiling bounds what the library accepts, not what the socket delivered, because react/stream buffers the body before the guard sees it.
Render cachesDiskCache stores finished bytes keyed by URL + size + protocol(+ mode detail) for cross-process redraws; AdaptiveImage is the in-session LRU; ImageLayer reserves marker blocks so images ride inside a text frame without wrecking layout.
tmux passthrough automationtmux panes swallow DCS/APC/OSC graphics unless allow-passthrough is on; TmuxPassthrough flips it pane-scoped for the render and restores (or unsets) it on retire — fail-soft, never a throw, opt-out via Detect::setAutoPassthrough(false).
Decode budgetsDecoding untrusted input is capped: 64 MiB read budget on the file, animated-file and URL routes (bytes already in hand are guarded by the format signature and the pixel budget instead of a length ceiling), a 50-megapixel per-decode ceiling re-checked on decoded dimensions, animated-GIF frame and cell budgets (a 256-frame slice plus per-frame and aggregate ceilings), and a bounded RIFF walk for WebP — every refusal cap pinned by tests.
Animation supportAnimation (immutable frame sequence) + AnimationDriver (Model with tick-based frame timing). Use KittyRenderer::renderFrame() for stable per-frame ids that support targeted redraws.

Source & demos

Try the quickstart →

Key Classes

ClassMethodDescription
Mosaicprobe()Auto-detect best terminal protocol
Mosaicsixel(), kitty(), iterm2(), halfBlock(), quarterBlock(), ascii(), symbols(), chafa()Force specific renderer
Mosaicprotocol(), modeDetail()Resolved backend name + per-mode detail (compose DiskCache keys from both)
Mosaicrender(image, ?width = null, ?height = null)Render image to ANSI string; a null width uses the builder's withResize() box
Mosaicbuilder()Create builder for fine-grained control
Rendererdelete(imageId)Remove a previously rendered image (Kitty=APC delete; iTerm2=OSC 1337 Pop; others=empty)
KittyRendererrenderWithOptions(image, width, height, KittyOptions)Render with Kitty protocol options (virtual-image store a=T,U=1 + control-only a=p; zlib o=z; raw-byte chunking)
KittyOptionstransmit(id), place(id, x, y)Factory: transmit (with or without storage) or place a previously stored image — place() emits a one-shot control-only a=p frame and never carries payload
KittyOptionswithZIndex(z), withCompression(f), withUseVirtual(bool), withPlacementU(u)Builder: z-index stacking, zlib compression (o=z), storing transmit (a=T,U=1 + trailing a=p), under/over-text placement (U=1 default, U=0 over text)
QuarterBlockRenderernew2×2 sub-pixel renderer via Mosaic::builder()->withRenderer(new QuarterBlockRenderer())
HalfBlockRenderernew, supportsAlpha()Unicode ▀ renderer with transparent-pixel handling (null alpha skips SGR codes, letting terminal default show through). supportsAlpha() returns false — transparency is rendered by omitting SGR, not blending.
SixelRenderernew(dither, maxColors, cellWidth, cellHeight, intensity), maxColors(), dither()DEC sixel renderer with median-cut quantizer (up to 256 colors). Constructor accepts maxColors (1–256, default 256) to limit palette size for limited-truecolor terminals — it reaches the facade only through Mosaic::builder()->withRenderer(new SixelRenderer(maxColors: 64)). The constructor also takes intensity (0.0–1.0 Ordered/Noise bias; null keeps the chafa config default 1.0), which Mosaic::sixel(dither, intensity) threads through. Dither enum: FloydSteinberg, Stucki, Atkinson, Ordered, Noise, None.
ImageSourcefromFile(path)Load image from file
ImageSourcefromGd(image, format)Create from GD resource; throws when the image cannot be encoded
ImageSourcefromString(bytes) / fromAnimatedFile(path)Decode any GD-readable bytes / load animated GIF or APNG frames as an Animation (frames + per-frame delays); animated WebP is refused by name (use chafa or sugar-video's AnimatedWebpDecoder)
ImageSourcefromUrl(url, headers) / fromUrlAsync(url)Fetch remote images with scheme + private-address SSRF floor (sync / ReactPHP)
DiskCacheget/put/getOrCompute, key()On-disk render cache; atomic writes, hashed keys, bounded entries
ImageLayerplace(bytes, w, h), placeTracked()Reserve marker blocks carrying image bytes in a text frame (dedup by content hash)
ImageSourceisPng()Whether the payload carries the PNG signature
Animationfixed(frames, delayMs)Factory: uniform-delay animation from list of ImageSource
AnimationwithFrame(index, frame, delayMs)Return new Animation with one replaced frame (immutable)
AnimationframeCount(), totalDurationMs()Frame count and total duration in ms
AnimationDrivernew(animation, renderer, cellWidth, cellHeight?, index?, paused?, imageId?)Model that drives Animation onto a Renderer via tick-based frame timing
AnimationDriverwithIndex(n), withPaused(bool), withImageId(id)Fluent state changes (each returns new instance)
FrameTickMsg(internal)Internal Msg dispatched by Cmd::tick() to advance frame index
KittyRendererrenderFrame(image, width, height, imageId)Render single frame with stable id for targeted delete+redraw on Kitty terminals

Demos.

VHS-recorded GIFs of every example shipped with the library. Regenerated automatically on every push that touches the source.

Terminal session rendering the bundled gradient fixture with the best available graphics protocol

Inline Image

Renders a PNG to the terminal via the best available protocol.