ndarray-pixels
v4.1.0
Published
ndarray-pixels
Downloads
120,723
Readme
ndarray-pixels
Convert ndarray ↔ image data, on Web and Node.js.
Designed to be used with other ndarray-based packages.
Supported Formats
| Platform | JPEG | PNG | Other | |----------|------|-----|-------------------------------------------------------------------------------------------------------| | Node.js | ✅ | ✅ | Based on sharp support | | 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));
// read
const pixels = await getPixels(bytesIn, 'image/png'); // Uint8Array -> ndarray
// modify
const [width, height] = pixels.shape;
for (let x = 0; x < width; ++x) {
for (let y = 0; y < height; ++y) {
pixels.set(x, y, 0, 255); // R
pixels.set(x, y, 1, 0.0); // G
pixels.set(x, y, 2, 0.0); // B
pixels.set(x, y, 3, 255); // A
}
}
// write
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');
// read
const pixels = await getPixels(bufferIn, 'image/png'); // Uint8Array -> ndarray
// modify
const [width, height] = pixels.shape;
for (let x = 0; x < width; ++x) {
for (let y = 0; y < height; ++y) {
pixels.set(x, y, 0, 255); // R
pixels.set(x, y, 1, 0.0); // G
pixels.set(x, y, 2, 0.0); // B
pixels.set(x, y, 3, 255); // A
}
}
// write
const bufferOut = await savePixels(pixels, 'image/png'); // ndarray -> Uint8Array
fs.writeFileSync('./output.png', bufferOut);