Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS canvas image data

Tags:

node.js

canvas

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?

like image 885
Krister Johansson Avatar asked Dec 24 '22 14:12

Krister Johansson


2 Answers

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

like image 117
Yoan Tournade Avatar answered Jan 14 '23 13:01

Yoan Tournade


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));
});
like image 24
Krister Johansson Avatar answered Jan 14 '23 11:01

Krister Johansson