Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs: convert pngjs stream to base64

I have a PNG object which I created using node-png and according the docs it's a "readable and writable Stream".

I would like to convert the PNG object to base64 and send it to the client via socket.io where I'll place the string in an image src.

I've tried many things but it seems that it's not trivial to convert a stream into a string.

Note that the data is created inside Node and not from the file system.

How can I achieve this?

like image 849
bymannan Avatar asked Feb 27 '14 22:02

bymannan


2 Answers

Here is what I did for future readers (this helped too):

png.pack();
var chunks = [];
png.on('data', function (chunk) {
  chunks.push(chunk);
  console.log('chunk:', chunk.length);
});
png.on('end', function () {
  var result = Buffer.concat(chunks);
  console.log('final result:', result.length);
  io.sockets.emit('image', result.toString('base64'));
});
like image 106
bymannan Avatar answered Nov 16 '22 04:11

bymannan


You do not want to convert the stream into a string but its readable chunk:

stream.on('readable', function() {
  var string = stream.read().toString('base64');

  // send through websocket  
});

You can also do this for the complete data running through the stream:

var data = '';

stream.on('readable', function() {
  data += stream.read().toString('base64');
});
stream.on('end', function() {
  console.log(data);
});

Depends on if the client requires the complete png picture to be available or if it is okay to have single chunks.

However if you are interested how this could look like in an practical example (with the image being uploaded by HTML5 Drag & Drop) you can checkout messenger.

like image 1
bodokaiser Avatar answered Nov 16 '22 02:11

bodokaiser