简体   繁体   中英

How to convert PNG image binary string to base64 without writing it to disk?

I successfully passed an image as binary string out of puppeteers page.evaluate() function back to node.js using:

async function getBinaryString(url) {
    return new Promise(async (resolve, reject) => {
        const reader = new FileReader();
        const response = await window.fetch(url)
        const data = await response.blob();
        reader.readAsBinaryString(data);
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject('Error occurred while reading binary string');
    });
}

I am able to save it with:

fs.writeFileSync(“image.png”, new Buffer.from(binaryString, "binary"), function (err) { });

But now I wish to convert this PNG image to base64 without saving it to file first because I will upload it to a different server. If I save it to file, I can do the following:

function base64Encode(file) {
    const bitmap = fs.readFileSync(file);                 
    return new Buffer.from(bitmap).toString('base64');
}

How do I skip the file saving part and get proper base64 data for my PNG ? I tried to pass binary string to new Buffer.from(binaryString).toString('base64') but I was unable to save it as a working PNG .

This doesn't really warrant answering my own question but @Jacob reminded me that I forgot to try:

new Buffer.from(binaryString, 'binary').toString('base64');

with a "binary" parameter, which solved the issue and PNG was correctly formatted again when going from base64 to file or to image in a browser.

Maybe the code in question can be reused by some other puppeteer user, it took me a while to come up with and find pieces across the web.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM