bymannan
bymannan

Reputation: 1383

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?

Upvotes: 16

Views: 27625

Answers (2)

bymannan
bymannan

Reputation: 1383

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

Upvotes: 24

bodokaiser
bodokaiser

Reputation: 15752

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.

Upvotes: 2

Related Questions