首页 > 解决方案 > 如何将PNG图像二进制字符串转换为base64而不将其写入磁盘?

问题描述

我使用以下方法成功地将图像作为二进制字符串从 puppeteerspage.evaluate()函数传回 node.js:

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

我可以通过以下方式保存它:

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

但现在我希望将此PNG图像转换为base64不先将其保存到文件,因为我会将其上传到不同的服务器。如果我将其保存到文件中,我可以执行以下操作:

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

如何跳过文件保存部分并base64为我获取正确的数据PNG?我试图将二进制字符串传递给,new Buffer.from(binaryString).toString('base64')但我无法将其保存为工作的PNG.

标签: javascriptnode.jspuppeteer

解决方案


这并不真正保证回答我自己的问题,但@Jacob 提醒我我忘了尝试:

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

带有一个"binary"参数,它解决了问题,并且在浏览器中从文件或图像转到文件PNG时再次正确格式化。base64

也许有问题的代码可以被其他 puppeteer 用户重用,我花了一段时间才想出并在网络上找到片段。


推荐阅读