[英]Difficulty converting image to Base64
I am facing a very confusing problem with converting an image to a base64 string in Node.js在 Node.js 中将图像转换为 base64 字符串时,我遇到了一个非常令人困惑的问题
Here is my example code:这是我的示例代码:
app.get('/image', (req, res) => {
ServerAPI.queryViewImage(options).then(image => {
res.render('image', { image: Buffer.from(image, 'binary').toString('base64') });
});
});
So basically, the most important thing is this chunk, where I am converting my image response to base64 string:所以基本上,最重要的是这个块,我将图像响应转换为 base64 字符串:
{ image: Buffer.from(image, 'binary').toString('base64') }
Actually, I tested my API with Postman and the image was displayed correctly.实际上,我用 Postman 测试了我的 API,图像显示正确。 Then, I converted the image to base64 using online converter and included the code in my html / img src, which worked.然后,我使用在线转换器将图像转换为 base64 并将代码包含在我的 html / img src 中,它有效。
Then I compared base64 code generated by Node.js and online converter from the same API call - obviously, there are differences.然后我比较了 Node.js 生成的 base64 代码和来自同一个 API 调用的在线转换器 - 显然,存在差异。 Screenshot below:截图如下:
differences between Node.js response to base64 and image to base64 Node.js 对 base64 的响应和图像对 base64 的区别
What I am missing?我错过了什么? Why is Node.js is not converting my image response correctly?为什么 Node.js 没有正确转换我的图像响应?
//EDIT: Including code of queryViewImage function. //编辑:包括queryViewImage函数的代码。
//basically, this function connects to server and returns image response as promise. rp() is from request-promise library
const queryViewImage = (token, siteId, viewId) => {
const options = {
method: 'GET',
url: `${url('sites')}/${siteId}/views/${viewId}/image`,
headers: {
'X-Tableau-Auth': token
}
};
return rp(options)
.then((response) => response)
.catch((err) => err);
}
I found a solution.我找到了解决方案。 Hopefully someone will use this in future.希望将来有人会使用它。
So, the request-promise library had some default encoding.所以,request-promise 库有一些默认编码。 To remove it, I added 'encoding' property to options object and set it to null.要删除它,我将“编码”属性添加到选项对象并将其设置为空。 As in below如下所示
const options = {
method: 'GET',
url: `${url('sites')}/${siteId}/views/${viewId}/image`,
headers: {
'X-Tableau-Auth': token
},
encoding: null
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.