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

问题描述 投票:0回答:2

我尝试使用got下载图像,并使用Buffer接口将其转换为base64编码的字符串,如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,它显示损坏的图像符号而不是所需的图像。

我的下载和编码方法是错误的还是我错过了其他的东西?我怎样才能缩小问题以修复此错误?

node.js image download base64 encode
2个回答
1
投票

没有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然后将其转换回来。


0
投票

为了完整性和人们,在将来绊倒我的问题,让我总结一下我的最终方法,该方法基于the accepted answer并预先修好所需的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)
© www.soinside.com 2019 - 2024. All rights reserved.