ndarray-pixels

ndarray-pixels

Usage no npm install needed!

<script type="module">
  import ndarrayPixels from 'https://cdn.skypack.dev/ndarray-pixels';
</script>

README

ndarray-pixels

Latest NPM release License Minzipped size CI

Convert ndarray ↔ image data, on Web and Node.js.

Designed to be used with other ndarray-based packages.

In Node.js, this package uses get-pixels and save-pixels. While both packages could be used on the web, they require polyfills for Node.js builtins. Browserify handles that automatically, but more modern bundlers do not. Moreover, the polyfills increase package size significantly. To avoid these problems, web builds of ndarray-pixels reimplement the same functionality with the more portable Canvas API.

Supported Formats

Platform JPEG PNG Other
Node.js
Web Based on browser support

Known Bugs

  • Web implementation (Canvas 2D) premultiplies alpha.

Quickstart

npm install --save ndarray-pixels

Web

import { getPixels, savePixels } from 'ndarray-pixels';

const bytesIn = await fetch('./input.png')
    .then((res) => res.arrayBuffer())
    .then((arrayBuffer) => new Uint8Array(arrayBuffer));

const pixels = await getPixels(bytesIn, 'image/png'); // Uint8Array -> ndarray

// ... modify ndarray ...

const bytesOut = await savePixels(pixels, 'image/png'); // ndarray -> Uint8Array

Node.js

const fs = require('fs');
const { getPixels, savePixels } = require('ndarray-pixels');

const bufferIn = fs.readFileSync('./input.png');
const pixels = await getPixels(bufferIn, 'image/png'); // Uint8Array -> ndarray

// ... modify ndarray ...

const bufferOut = await savePixels(pixels, 'image/png'); // ndarray -> Uint8Array
fs.writeFileSync('./output.png', bufferOut);

API

getPixels

getPixels(data: string | Uint8Array, mimeType?: string): Promise<ndarray>

Decodes image data to an ndarray.

MIME type is optional when given a path or URL, and required when given a Uint8Array.

Accepts image/png or image/jpeg in Node.js, and additional formats on browsers with the necessary support in Canvas 2D.

Parameters:

Name Type Description
data string | Uint8Array
mimeType? string image/jpeg, image/png, etc.

Returns: Promise<ndarray>

Defined in: index.ts:17


savePixels

savePixels(pixels: ndarray, mimeType: string): Promise<Uint8Array>

Encodes an ndarray as image data in the given format.

If the source ndarray was constructed manually with default stride, use ndarray.transpose(1, 0) to reshape it and ensure an identical result from getPixels(). For an ndarray created by getPixels(), this isn't necessary.

Accepts image/png or image/jpeg in Node.js, and additional formats on browsers with the necessary support in Canvas 2D.

Parameters:

Name Type Description
pixels ndarray ndarray of shape W x H x 4.
mimeType string image/jpeg, image/png, etc.

Returns: Promise<Uint8Array>

Defined in: index.ts:48