Display images in the terminal

Overview

terminal-image

Display images in the terminal

Works in any terminal that supports colors.

In iTerm, the image will be displayed in full resolution, since iTerm has special image support.

Install

$ npm install terminal-image

Usage

import terminalImage from 'terminal-image';

console.log(await terminalImage.file('unicorn.jpg'));

Optionally, you can specify the height and/or width to scale the image. That can be either the percentage of the terminal window or number of rows and/or columns. Please note that the image will always be scaled to fit the size of the terminal. If width and height are not defined, by default the image will take the width and height of the terminal.

It is recommended to use the percentage option.

import terminalImage from 'terminal-image';

console.log(await terminalImage.file('unicorn.jpg', {width: '50%', height: '50%'}));

You can set width and/or height as columns and/or rows of the terminal window as well.

import terminalImage from 'terminal-image';

console.log(await terminalImage.file('unicorn.jpg', {width: 50}));

By default, aspect ratio is always maintained. If you don't want to maintain aspect ratio, set preserveAspectRatio to false. However, your image will be scaled to fit the size of the terminal.

import terminalImage from 'terminal-image';

console.log(await terminalImage.file('unicorn.jpg', {width: 70, height: 50, preserveAspectRatio: false}));

API

Supports PNG and JPEG images. Animated GIFs are also supported with .gifBuffer and .gifFile.

terminalImage.buffer(imageBuffer, options?)

terminalImage.file(filePath, options?)

Returns a Promise<string> with the ANSI escape codes to display the image.

terminalImage.gifBuffer(imageBuffer, options?)

terminalImage.gifFile(filePath, options?)

Returns a function that can be called to stop the GIF animation.

options

Type: object

height

Type: string | number

Custom image height.

Can be set as percentage or number of rows of the terminal. It is recommended to use the percentage options.

width

Type: string | number

Custom image width.

Can be set as percentage or number of columns of the terminal. It is recommended to use the percentage options.

preserveAspectRatio

Type: boolean
Default: true

Whether to maintain image aspect ratio or not.

maximumFrameRate

Only works for terminalImage.gifBuffer or terminalImage.gifFile

Type: number
Default: 30

Maximum framerate to render the GIF. This option is ignored when using iTerm.

renderFrame

Only works for terminalImage.gifBuffer or terminalImage.gifFile

Type: (text: string) => void
Default: log-update

Custom handler which is run for each frame of the GIF.

This can be set to change how each frame is shown.

renderFrame.done

Only works for terminalImage.gifBuffer or terminalImage.gifFile

Type: () => void
Default: log-update

Custom handler which is run when the animation playback is stopped.

This can be set to perform a cleanup when playback has finished.

Tip

Display a remote image

import terminalImage from 'terminal-image';
import got from 'got';

const body = await got('https://sindresorhus.com/unicorn').buffer();
console.log(await terminalImage.buffer(body));

Related

Comments
  • Support animated GIFs

    Support animated GIFs

    After many hours of debugging, I've finally managed to find a way to draw gif frames in the terminal. iTerm also supports embedding gifs since version 2.9.20150512 but then the stopAnimation function would have to be a noop and be conditionally executed.

    A slight problem I'm noticing is that the terminal can only handle so many characters being logged at once so it lags behind a bit.

    Test script output

    Fixes: #2

    cc @sindresorhus

    opened by Richienb 28
  • Add `width` and `height` option

    Add `width` and `height` option

    This pull-request add support for optional width and height options, auto-adjusting size if any (or both) of them is not defined, also when running in Windows. It also unify the file and buffer functions, and fix two bugs related to alpha channel and when resized image has an odd number of rows.

    opened by piranna 14
  • Render raw pixel data from ArrayBuffer source

    Render raw pixel data from ArrayBuffer source

    How hard would it be to support rendering raw ArrayBuffer pixel data like how CanvasRenderingContext2D works in browsers? I'd also love to help with this support if I can get pointed in the right direction! :)

    opened by jozanza 8
  • Add option to scale images. Closes #1

    Add option to scale images. Closes #1

    Hi @sindresorhus 😊

    I have created a PR to scale images, as requested in #1.

    Since I wanted to keep the aspect-ratio, I only introduced a single factor parameter, not separate options for width and height.

    I hope you like the changes 😊

    opened by goloroden 5
  • Legacy versions of mkdirp are no longer supported.

    Legacy versions of mkdirp are no longer supported.

    Cannot install I'm getting an error by npm-

    npm WARN deprecated [email protected]: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.) npm ERR! code ENOENT npm ERR! syscall spawn git npm ERR! path git npm ERR! errno -4058 npm ERR! enoent Error while executing: npm ERR! enoent undefined ls-remote -h -t ssh://[email protected]/notmasteryet/jpgjs.git npm ERR! enoent npm ERR! enoent npm ERR! enoent spawn git ENOENT npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent

    npm ERR! A complete log of this run can be found in:

    opened by zedd3v 3
  • Remove conversion to buffer

    Remove conversion to buffer

    https://github.com/sindresorhus/terminal-image/blob/a659386d84576c645c69fb43e3517d4030223d66/index.js#L47

    Both term-img and jimp accept as first parameter both a buffer of a filepath, so usage of readFIle() is superfluous and also add some limits...

    opened by piranna 3
  • Only file and data URLs are supported by the default ESM

    Only file and data URLs are supported by the default ESM

    Not sure why, but I get this error when I try to import the library:

    internal/process/esm_loader.js:74
        internalBinding('errors').triggerUncaughtException(
                                  ^
    
    Error [ERR_UNSUPPORTED_ESM_URL_SCHEME]: Only file and data URLs are supported by the default ESM loader. Received protocol 'node:'
        at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:750:11)
        at Loader.resolve (internal/modules/esm/loader.js:85:40)
        at Loader.getModuleJob (internal/modules/esm/loader.js:229:28)
        at ModuleWrap.<anonymous> (internal/modules/esm/module_job.js:51:40)
        at link (internal/modules/esm/module_job.js:50:36) {
      code: 'ERR_UNSUPPORTED_ESM_URL_SCHEME'
    }```
    opened by NoahCardoza 2
  • CommonJS module

    CommonJS module

    Hi! I was wondering if there's a CommonJS version of this module for use in NodeJS? All my other modules are in CommonJS and if I set "type": "module" in my package.json it will break all the rest.

    Thank you.

    opened by LinkTree3 2
  • Switching from Chalk to Colorette to reduce file size.

    Switching from Chalk to Colorette to reduce file size.

    opened by equinusocio 2
  • Finish #7

    Finish #7

    Issuehunt badges

    Would be nice to have https://github.com/sindresorhus/terminal-image/pull/7 finished, but the PR submitter is not responding.

    Looking for someone to finish that PR and address the PR feedback. Preserve the existing commits and just add new ones in a new PR>


    IssueHunt Summary

    baidaly baidaly has been rewarded.

    Backers (Total: $40.00)

    Submitted pull Requests


    Tips

    help wanted :gift: Rewarded on Issuehunt 
    opened by sindresorhus 2
  • Add new method that accepts raw pixel image data

    Add new method that accepts raw pixel image data

    Description This PR adds a new method for converting "ImageData" as described in #4

    Changes

    • Refactored render() function body into 2 smaller functions: scaleImage and renderImage
    • Added new imageDataToImage() function for converting ImageData to a Jimp instance
    • Added new export imageData()
    • Updated README with imageData() method docs

    Testing I created a new test case to cover the update, however, I think I could use some help identifying whether or not this method works as expected.

    Additional Info Although the passed imageData provides RGBA pixel data, right now, this implementation will ignore the alpha channel. I want to get a few eyes on this before I dive in further into any specific issue.

    Anyways, let me know what to change/fix @sindresorhus 👍


    Fixes #4

    opened by jozanza 2
  • B/W Image problem

    B/W Image problem

    Whenever I try to make it render a black and white image, it just prints a bunch of white, Any fix? My entire code is literally just this: const terminalImage = require('terminal-image'); (async () => { console.log(await terminalImage.file(frames/out20.png)); })();

    opened by GamingMidi 1
  • Compatibility with cli-table?

    Compatibility with cli-table?

    Doing a quick test to see if I can use this with https://github.com/Automattic/cli-table ...

    const terminalImage = require('terminal-image');
    const Table = require('cli-table');
    
    (async () => {
    	const img = await terminalImage.file(process.argv[2], {width: 50, height: 50});
    
    	const table = new Table({head: ['img', 'caption']});
    	table.push([img, 'description #1'], [img, 'description #2']);
    	console.log(table.toString());
    })();
    

    It works nicely in macOS native terminal:

    Screen Shot 2020-08-13 at 12 03 56 PM

    But in iTerm 2 I'm getting a screen full of lines, like the table thinks the output is (much) larger than it is. Customizing row widths in cli-table doesn't seem to help. Any idea if this is something I could reasonably expect to work, or just incompatible with whatever special image rendering iTerm 2 has? Maybe related to #29? Thanks!

    enhancement help wanted 
    opened by donmccurdy 2
  • Is that possible to get a render quality as Ranger file manager has?

    Is that possible to get a render quality as Ranger file manager has?

    Ranger file manager (linux) can show images preview (via w3m as far as I know) a lot way better than terminal-image. Is that possible to get such quality? Ranger shows in terminal exactly the source quality of an image.

    opened by ProgrammingLife 4
Releases(v2.0.0)
Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Wants more empathy & kindness in open source. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns
Sindre Sorhus
Terminal ui for discord with interactive terminal

dickord why No fucking clue i was bored or something. why does it look dogshit Try and find a node module that supports terminal functions like trauma

Hima 3 Nov 7, 2022
Sublime-like terminal-based text editor

slap ?? slap is a Sublime-like terminal-based text editor that strives to make editing from the terminal easier. It has: first-class mouse support (ev

slap 6.1k Jan 1, 2023
A terminal-to-gif recorder minus the headaches.

ttystudio A terminal-to-gif recorder minus the headaches. Record your terminal and compile it to a GIF or APNG without any external dependencies, bash

Christopher Jeffrey (JJ) 3.2k Dec 23, 2022
rtail(1) - Terminal output to the browser in seconds, using UNIX pipes.

rtail(1) Terminal output to the browser in seconds, using UNIX pipes. rtail is a command line utility that grabs every line in stdin and broadcasts it

Kilian Ciuffolo 1.6k Jan 6, 2023
Pipeable javascript. Quickly filter, map, and reduce from the terminal

Pipeable JavaScript - another utility like sed/awk/wc... but with JS! Quickly filter, map and reduce from the command line. Features a streaming API.

Daniel St. Jules 410 Dec 10, 2022
Translations with speech synthesis in your terminal as a node package

Normit Normit is an easy way to translate stuff in your terminal. You can check out its Ruby gem version termit. Installation npm install normit -g Us

Paweł Urbanek 234 Jan 1, 2023
Terminal recorder: Record your termial session into HTML

terminal-recorder Terminal recorder allows you to record your bash session, and export it to html so then you can share it with your friends. GitHub P

Cristian Cortez 104 Mar 3, 2022
Terminal task list

listr Terminal task list Install $ npm install --save listr Usage const execa = require('execa'); const Listr = require('listr'); const tasks = new

Sam Verschueren 3.1k Jan 3, 2023
📜 Create mutable log lines into the terminal, and give life to your logs!

Because Logging can be pretty and fun Installation $ npm install draftlog What it does It allows you to re-write a line of your log after being writt

Ivan Seidel 1.2k Dec 31, 2022
:rainbow: Beautiful color gradients in terminal output

gradient-string Beautiful color gradients in terminal output Install $ npm i gradient-string Usage const gradient = require('gradient-string'); cons

Boris K 864 Jan 3, 2023
Create clickable links in the terminal

terminal-link Create clickable links in the terminal Install $ npm install terminal-link Usage import terminalLink from 'terminal-link'; const link

Sindre Sorhus 539 Dec 31, 2022
Reliably get the terminal window size

term-size Reliably get the terminal window size Because process.stdout.columns doesn't exist when run non-interactively, for example, in a child proce

Sindre Sorhus 132 Oct 11, 2022
Truncate a string to a specific width in the terminal

cli-truncate Truncate a string to a specific width in the terminal Gracefully handles ANSI escapes. Like a string styled with chalk. It also supports

Sindre Sorhus 78 Oct 10, 2022
Execute shell commands in terminal

Execute shell commands in terminal

skanehira 9 Dec 11, 2021
Add a hungry turtle to your terminal and feed it every time you mistype 'npm' as 'nom'

Nom Does this ever happen to you? You happily code away on a project, navigating the command line like a pro, testing, error logging, installing packa

Meike Hankewicz 5 Apr 26, 2022
Just a minimal library to do some terminal stuff.

Termctl A simple library to do some basic terminal stuff. Usage const termctl = require("termctl"); Note: We have tested this on Linux Mint and Window

Biraj 4 Sep 28, 2021
A terminal for a more modern age

Downloads: Latest release Repositories: Debian/Ubuntu-based, RPM-based Latest nightly build This README is also available in: Korean 简体中文 Tabby (forme

null 41.8k Dec 30, 2022
DataENV is a cli tool that allows you to save data temporarily using your terminal.

DataEnv CLI Instllation npm install -g dataenv Usage Table of Contents LocalStorage npx dataenv save Parameters npx dataenv show Parameters npx dataen

PGamerX 2 Feb 5, 2022