难以将图像转换为 Base64
Difficulty converting image to Base64
我在 Node.js
中将图像转换为 base64 字符串时遇到了一个非常令人困惑的问题
这是我的示例代码:
app.get('/image', (req, res) => {
ServerAPI.queryViewImage(options).then(image => {
res.render('image', { image: Buffer.from(image, 'binary').toString('base64') });
});
});
所以基本上,最重要的是这个块,我在这里将我的图像响应转换为 base64 字符串:
{ image: Buffer.from(image, 'binary').toString('base64') }
实际上,我用 Postman 测试了我的 API,图像显示正确。然后,我使用在线转换器将图像转换为 base64,并将代码包含在我的 html / img src 中,它起作用了。
然后我比较了 Node.js 生成的 base64 代码和来自同一 API 调用的在线转换器 - 显然,存在差异。截图如下:
differences between Node.js response to base64 and image to base64
我错过了什么?为什么 Node.js 没有正确转换我的图像响应?
//编辑:
包括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);
}
我找到了解决办法。希望将来有人会用到它。
所以,请求-承诺库有一些默认编码。要删除它,我将 'encoding' 属性 添加到选项对象并将其设置为空。如下图
const options = {
method: 'GET',
url: `${url('sites')}/${siteId}/views/${viewId}/image`,
headers: {
'X-Tableau-Auth': token
},
encoding: null
};
我在 Node.js
中将图像转换为 base64 字符串时遇到了一个非常令人困惑的问题这是我的示例代码:
app.get('/image', (req, res) => {
ServerAPI.queryViewImage(options).then(image => {
res.render('image', { image: Buffer.from(image, 'binary').toString('base64') });
});
});
所以基本上,最重要的是这个块,我在这里将我的图像响应转换为 base64 字符串:
{ image: Buffer.from(image, 'binary').toString('base64') }
实际上,我用 Postman 测试了我的 API,图像显示正确。然后,我使用在线转换器将图像转换为 base64,并将代码包含在我的 html / img src 中,它起作用了。
然后我比较了 Node.js 生成的 base64 代码和来自同一 API 调用的在线转换器 - 显然,存在差异。截图如下:
differences between Node.js response to base64 and image to base64
我错过了什么?为什么 Node.js 没有正确转换我的图像响应?
//编辑: 包括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);
}
我找到了解决办法。希望将来有人会用到它。
所以,请求-承诺库有一些默认编码。要删除它,我将 'encoding' 属性 添加到选项对象并将其设置为空。如下图
const options = {
method: 'GET',
url: `${url('sites')}/${siteId}/views/${viewId}/image`,
headers: {
'X-Tableau-Auth': token
},
encoding: null
};