node-pureimage
node-pureimage copied to clipboard
Get PNG data as a Buffer
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.
FYI: I can same thing with get-stream package
const stream = new PassThrough()
await encodePNGToStream(img, stream)
const buffer = await getStream.buffer(stream)
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.
I've added a new example to the readme using your technique. Thanks!