Node JS canvas image data

11,877

Solution 1

To strictly answer the question:

So is there a another way to go without using Canvas?

The issue is that, even if we can load an image binary data, we need to be able to parse its binary format to represent it as raw pixel data (ImageData/Uint8Array objects).

This is why the canvas module needs to be compiled when installed: it rely on and links to libpng, libjpeg and other native libraries.

To load a Uint8Array representing pixel raw data from a file, without canvas (or native library wrapper), will requires decoders running only in Javascript.

For e.g. there exist decoders for png and jpeg as third-party libraries.

Decoding PNG

Using png.js:

const PNG = require('png-js');
PNG.decode('./image.png', function(pixels) {
   // Pixels is a 1d array (in rgba order) of decoded pixel data
});

Decoding JPEG

Using inkjet:

const inkjet = require('inkjet');
inkjet.decode(fs.readFileSync('./image.jpg'), function(err, decoded) {
  // decoded: { width: number, height: number, data: Uint8Array }
});

https://github.com/gchudnov/inkjet

Solution 2

Do not realy know what i did to get canvas to work. I used pixel-util to set image data.

var pixelUtil = require('pixel-util'),
    Canvas = require('canvas');

var image = new Canvas.Image,

pixelUtil.createBuffer('http://127.0.0.1:8080/image/test.jpg').then(function(buffer){
    image.src = buffer;

    canvas = new Canvas(image.width, image.height);

    var ctx = canvas.getContext('2d');
    ctx.drawImage(image, 0, 0);
    runImage(ctx.getImageData(0, 0, canvas.width, canvas.height));
});
Share:
11,877
Krister Johansson
Author by

Krister Johansson

Programer from Sweden that loves to work in NodeJS

Updated on June 04, 2022

Comments

  • Krister Johansson
    Krister Johansson almost 2 years

    I am trying to read a image and the result i want to get is the same when you use a HTML canvas "Uint8ClampedArray"? var imageData = ctx.getImageData(0, 0, width, height); I found a NPM lib canvas but i cant get it to install.

    So is there a another way to go without using Canvas?