【问题标题】:Downloading and converting image to base64 results in corrupted data下载图像并将其转换为 base64 会导致数据损坏
【发布时间】:2019-04-01 12:43:05
【问题描述】:

我尝试使用got 下载图像,并使用responsetype 的Buffer 接口将其转换为base64 编码的字符串。我当前的 sn-p 转换图像并将编码的字符串记录到控制台:

'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


    【解决方案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,然后再将其转换回来。

    【讨论】:

    • data:image/png;base64 是编码字符串的必需部分吗?您知道如何将此部分添加到编码输出中吗?我可以手动预先挂起,但我只是想知道如何自动执行此操作,从而更灵活/优雅。
    • 如果你需要的话,你必须在前面加上它。如果您想在浏览器的img 标记中显示它,这是“强制性的”。这取决于用例。
    【解决方案2】:

    为了完整和人们,将来偶然发现我的问题,让我总结一下我基于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)
    

    【讨论】:

      猜你喜欢
      • 2017-06-10
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多