Converted base64 image does not work, how can I ge

2019-07-13 22:13发布

问题:

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);
    }
});