Krister Johansson
Krister Johansson

Reputation: 711

Node JS canvas image data

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?

Upvotes: 4

Views: 15777

Answers (2)

Yoan Tournade
Yoan Tournade

Reputation: 713

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

Upvotes: 7

Krister Johansson
Krister Johansson

Reputation: 711

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

Upvotes: 4

Related Questions