简体   繁体   中英

Difficulty converting image to Base64

I am facing a very confusing problem with converting an image to a base64 string in Node.js

Here is my example code:

app.get('/image', (req, res) => {
  ServerAPI.queryViewImage(options).then(image => {
    res.render('image', { image: Buffer.from(image, 'binary').toString('base64') });
  });
});

So basically, the most important thing is this chunk, where I am converting my image response to base64 string:

 { image: Buffer.from(image, 'binary').toString('base64') }

Actually, I tested my API with Postman and the image was displayed correctly. Then, I converted the image to base64 using online converter and included the code in my html / img src, which worked.

Then I compared base64 code generated by Node.js and online converter from the same API call - obviously, there are differences. Screenshot below:

differences between Node.js response to base64 and image to base64

What I am missing? Why is Node.js is not converting my image response correctly?

//EDIT: Including code of queryViewImage function.

//basically, this function connects to server and returns image response as promise. rp() is from request-promise library
const queryViewImage = (token, siteId, viewId) => {
    const options = {
        method: 'GET',
        url: `${url('sites')}/${siteId}/views/${viewId}/image`,
        headers: {
            'X-Tableau-Auth': token
        }
    };

    return rp(options)
        .then((response) => response)
        .catch((err) => err);
}

I found a solution. Hopefully someone will use this in future.

So, the request-promise library had some default encoding. To remove it, I added 'encoding' property to options object and set it to null. As in below

    const options = {
        method: 'GET',
        url: `${url('sites')}/${siteId}/views/${viewId}/image`,
        headers: {
            'X-Tableau-Auth': token
        },
        encoding: null
    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM