Code Monkey home page Code Monkey logo

terminal-image's Introduction

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

terminal-image's People

Contributors

baidaly avatar bendingbender avatar richienb avatar sindresorhus avatar splars avatar whoaa512 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

terminal-image's Issues

SyntaxError: Cannot use import statement outside a module

When attempting to import into a Typescript project.

import fs, {promises as fsPromises} from 'node:fs';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)

Support setting width/height

Should be easy to support this through an options object, but I didn't want to do it before anyone had a need for it. PR welcome if so.

Remove conversion to buffer

exports.file = async filePath => exports.buffer(await readFile(filePath));

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...

Image conversion

Will the ability to rotate or resize the image through the option be added?

SIXEL support?

For higher quality images you might want to add optional SIXEL output (supported by several terminals).

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.

ERR_REQUIRE_ESM

When I run with ts-node I have next error

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /node_modules/terminal-image/index.js
require() of ES modules is not supported.
require() of /node_modules/terminal-image/index.js from /src/cli/commands/new/newCommand.ts is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /node_modules/terminal-image/package.json.

    at new NodeError (node:internal/errors:363:5)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1112:13)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:816:12)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:93:18)
    at Object.<anonymous> (/src/cli/commands/new/newCommand.ts:10:1)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Module.m._compile (/ts-node/src/index.ts:1295:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

How to use image buffer in axios ?

const terminalImage = require('terminal-image');
const axios = require('axios');

const run = async () => {
    let image = null;
    try {
        image = await axios.get('https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png');
        console.log(image.data);
    } catch (err) {
        console.log(err.message);
    }
    
    if (image.data) {
        console.log(await terminalImage.buffer(image.data));
    }
}

run();

I would like to know what I am doing wrong.

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!

Fails to install with npm install

When trying to install this package with npm, it stops at
$ npm install --save terminal-image ⸨ ░░░░░░░░░░░░░░░░░⸩ ⠦ fetchMetadata: sill resolveWithNewModule [email protected] checking installable status and does not proceed.

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'
}```

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! :)

Move fallback to own module?

I find the fallback to have enough entity to work standalone. What about moving it to it's own module and use it as dependency of this one? It would also allow to make it without behaviour constrains to be the same as term-img, doing that constrains in this module instead...

Finish #7

Issuehunt badges

Would be nice to have #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

how to display a remote image from a public url

I am following the docs and trying to show an image from a url online, but I must be missing something as it is not displaying. Code is below, can you see what I can do differently to fetch and display the image?

const terminalImage = require('terminal-image');
const got = require('got');

(async () => {
	const {body} = await got('https://vignette.wikia.nocookie.net/prowrestling/images/c/c5/Bret-Hart.jpg', {encoding: null});
	console.log(await terminalImage.buffer(body));
})();

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:

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)); })();

CommonJS support

The lib doesn't work with node out of the box. To require with commonjs we have to do some wizardry like this:

(async () => {
    const terminalImage = (await import("terminal-image")).default;
    console.log(await terminalImage.file('pikachu.png'));
})();

While requiring a commonjs lib on a ESM file is quite simple:

import someCommonJsLib from "some-commonjs-lib";

Consider reverting back to common js.

Anyway, thanks for the wonderfull library.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.