下载图像并将其转换为 base64 会导致数据损坏

Downloading and converting image to base64 results in corrupted data

我尝试使用 got and convert it to a base64-encoded string using a Buffer interface as responsetype 下载图像。我当前的代码片段转换图像并将编码后的字符串记录到控制台:

'use strict';

const got = require('got');
const imgUrl = 'https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'


got(imgUrl, {
    responseType: 'buffer'
})
.then(response => Buffer.from(response.body, 'binary').toString('base64'))
.then(console.log)

我通过将任何终端输出重定向到文件,将 base64 编码的字符串写入文件,如下所示:

node base64.js >> base64_image

我打开文件并将其内容复制到一个 online base64-image-viewer,它显示的是损坏的图像符号,而不是所需的图像。

是我的下载和编码方法有问题还是我遗漏了什么?我怎样才能缩小问题范围以修复此错误?

没有responseType属性。您必须使用 encoding 属性,默认为 utf8

got(imgUrl, {
    encoding: null
})
.then(response => response.body.toString('base64'))
.then(console.log)

或直接:encoding: 'base64'

got(imgUrl, {
        encoding: 'base64'
    })
    .then(response => response.body)
    .then(console.log)

否则您将尝试从 utf8 编码图像转换回来,这就是它损坏的原因。您不能将图像转换为 utf8 然后再将其转换回来。

为了完整性和为了人们,在未来绊倒我的问题,让我总结一下我的最终方法,它基于 并预先考虑所需的 data:image/png;base64

'use strict';

const got = require('got');

const imgUrl = 'https://www.google.de/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png'


got(imgUrl, {
    encoding: 'base64'
})
.then(response => {
    const contentType = response.headers["content-type"];
    const imgData = response.body;
    const encodedImage = `data:${contentType};base64,${imgData}`;
    return encodedImage;
})
.then(console.log)