ndarray-pixels
Convert ndarray ↔ image data, on Web and Node.js.
Designed to be used with other ndarray-based packages.
Supported Formats
Known Bugs
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');
for (let i = 0; i < pixels.shape[0]; ++i) {
for (let j = 0; j < pixels.shape[1]; ++j) {
pixels.set(i, j, 255);
}
}
const bytesOut = await savePixels(pixels, 'image/png');
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');
for (let i = 0; i < pixels.shape[0]; ++i) {
for (let j = 0; j < pixels.shape[1]; ++j) {
pixels.set(i, j, 255);
}
}
const bufferOut = await savePixels(pixels, 'image/png');
fs.writeFileSync('./output.png', bufferOut);
API
getPixels
▸ getPixels(data
, mimeType
): Promise
<NdArray
<Uint8Array
>>
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 | Uint8Array | |
mimeType | string | image/jpeg , image/png , etc. |
Returns
Promise
<NdArray
<Uint8Array
>>
Defined in
index.ts:17
savePixels
▸ savePixels(pixels
, mimeType
): 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 <Uint8Array | Uint8ClampedArray > | ndarray of shape W x H x 4. |
mimeType | string | image/jpeg , image/png , etc. |
Returns
Promise
<Uint8Array
>
Defined in
index.ts:35