Converted base64 image does not work, how can I get true base64 image?

浪尽此生 提交于 2019-12-23 18:34:12

问题


I try to convert my request payload to base64 but the result of my code is not a valid base64 image. When I try to use it in the browser, it doesn't display the image.

So I try to write simple code to convert image to base64 or using npm modules but the result is the same and I don't get a valid image!

const request = require('request');

const url = "http://cdn1.giltcdn.com/images/share/uploads/0000/0001/7250/172502872/420x560.jpg";

request({url, gzip: true}, function (err, res, body) {

    if(!err){
        const data = "data:" + res.headers["content-type"] + ";base64," + Buffer.from(body, 'binary').toString('base64');
        console.log(data);
    }
});

or

server.get("/test", function(req, res){
    const data = "data:" + req.headers["content-type"] + ";base64," + Buffer.from(req.data.payload, 'binary').toString('base64');
    console.log(data);
});

The result is the same (when i copy and paste in browser, it doesn't display the image):

data:image/jpeg;base64,/f39/QAQSkZJRgABAQAAAQABAAD9/QBDAAEBA...

When i used this https://www.base64-image.de/ website for converting to base64 image, the result is (when i copy and paste in browser, it works and displays the image):

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBA...

Why are the results different and why doesn't buffer to base64 work?


回答1:


It seems like you need to set encoding: null as an option for the request function, as explained in this answer. It forces the body to be returned as binary instead of utf8 which is the default.

const request = require('request');

const url = "http://cdn1.giltcdn.com/images/share/uploads/0000/0001/7250/172502872/420x560.jpg";

request({url, gzip: true, encoding: null}, function (err, res, body) {
    if(!err) {
        const data = "data:" + res.headers["content-type"] + ";base64," + Buffer.from(body, 'binary').toString('base64');
        console.log(data);
    }
});


来源:https://stackoverflow.com/questions/53126113/converted-base64-image-does-not-work-how-can-i-get-true-base64-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!