javascript - 如何将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
.
解决方案
这并不真正保证回答我自己的问题,但@Jacob 提醒我我忘了尝试:
new Buffer.from(binaryString, 'binary').toString('base64');
带有一个"binary"
参数,它解决了问题,并且在浏览器中从文件或图像转到文件PNG
时再次正确格式化。base64
也许有问题的代码可以被其他 puppeteer 用户重用,我花了一段时间才想出并在网络上找到片段。
推荐阅读
- discord - Discord.js 禁用 @evereyone 访问新频道
- ios - Xcode 打开全窗口模式
- html - 为什么元素显示底部填充和底部边框以及顶部边框和顶部填充搞砸了?
- angular - 检查来自 HTTP POST 请求的响应是否为 200
- jquery - 如何去除嵌套表格和表格行之间的间距
- lua - 无法在 lua 的播放器中获取值
- angular - 根据选项卡选择隐藏角度选择选项
- d3.js - 如何混合有用的自动生成的记号(),同时还指定您希望记号间隔下降到的最低粒度
- python - “启动器中的致命错误:”使用 pip 或烧瓶时
- c# - 如何使用公共 void 方法但私有成员测试代码?