node-pureimage icon indicating copy to clipboard operation
node-pureimage copied to clipboard

Get PNG data as a Buffer

Open joeytwiddle opened this issue 6 years ago • 1 comments

I wanted to get the PNG data as a buffer instead of a stream (because I am returning the data to the Loopback4 framework).

Using the tests for inspiration, I came up with this:


async function encodePNGToBuffer(canvas) {
  return encodeAndStreamIntoBuffer(pureimage.encodePNGToStream, canvas);
}

async function encodeJPEGToBuffer(canvas) {
  return encodeAndStreamIntoBuffer(pureimage.encodeJPEGToStream, canvas);
}

async function encodeAndStreamIntoBuffer(encodeDataToStream, canvas) {
  const PassThrough = require('stream').PassThrough;
  const passThroughStream = new PassThrough();
  const pngData = [];
  passThroughStream.on('data', chunk => pngData.push(chunk));
  passThroughStream.on('end', () => {});
  await encodeDataToStream(canvas, passThroughStream);
  return Buffer.concat(pngData);
}

You are welcome to include these in the library if you like.

I would also be interested to hear if anyone knows a better way.

joeytwiddle avatar Jul 29 '19 02:07 joeytwiddle

FYI: I can same thing with get-stream package

  const stream = new PassThrough()
  await encodePNGToStream(img, stream)
  const buffer = await getStream.buffer(stream)

terrierscript avatar Aug 09 '21 13:08 terrierscript

Wow thanks so much for this!!! I've been looking for a way to achieve something like the canvas method toDataURL. I can finally do it thanks to your code! I then turn the buffer into base64 with buffer.toString('base64') and then I can show it directly on an API I'm doing. Thanks!

I wanted to get the PNG data as a buffer instead of a stream (because I am returning the data to the Loopback4 framework).

Using the tests for inspiration, I came up with this:

async function encodePNGToBuffer(canvas) {
  return encodeAndStreamIntoBuffer(pureimage.encodePNGToStream, canvas);
}

async function encodeJPEGToBuffer(canvas) {
  return encodeAndStreamIntoBuffer(pureimage.encodeJPEGToStream, canvas);
}

async function encodeAndStreamIntoBuffer(encodeDataToStream, canvas) {
  const PassThrough = require('stream').PassThrough;
  const passThroughStream = new PassThrough();
  const pngData = [];
  passThroughStream.on('data', chunk => pngData.push(chunk));
  passThroughStream.on('end', () => {});
  await encodeDataToStream(canvas, passThroughStream);
  return Buffer.concat(pngData);
}

You are welcome to include these in the library if you like.

I would also be interested to hear if anyone knows a better way.

merchedev avatar Dec 03 '22 14:12 merchedev

I've added a new example to the readme using your technique. Thanks!

joshmarinacci avatar Dec 27 '22 02:12 joshmarinacci