Axios: How to transform image from get request to base64

Created on 1 Nov 2016  ·  10Comments  ·  Source: axios/axios

any libs out there in npm that can do this?

axios.get('http://www.freeiconspng.com/uploads/profile-icon-9.png', {
   transformRequest: [function (data) {
       return data;
   }],
  transformResponse: [function (data) {
    return data;
  }],
});

Most helpful comment

if you are on node like me and you are using v >= 6, there was a change and you should use Buffer.from or similar.

function getBase64(url) {
  return axios
    .get(url, {
      responseType: 'arraybuffer'
    })
    .then(response => Buffer.from(response.data, 'binary').toString('base64'))
}

Reference safe-buffer
new Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead

All 10 comments

I think this is a question for StackOverflow.

for anyone searching for the solution, I have the following code:

get('/getImg', {
    responseType: 'arraybuffer' 
})
.then(function(result) {
    console.log(_imageEncode(result.data))
})
function _imageEncode (arrayBuffer) {
    let u8 = new Uint8Array(arrayBuffer)
    let b64encoded = btoa([].reduce.call(new Uint8Array(arrayBuffer),function(p,c){return p+String.fromCharCode(c)},''))
    let mimetype="image/jpeg"
    return "data:"+mimetype+";base64,"+b64encoded
}

This was our solution, it works like a charm

return axios.get('http://example.com/image.png', { responseType: 'arraybuffer' })
      .then((response) => {
        let image = btoa(
          new Uint8Array(response.data)
            .reduce((data, byte) => data + String.fromCharCode(byte), '')
        );
        return `data:${response.headers['content-type'].toLowerCase()};base64,${image}`;
      });

The reason this won't work is that axios puts everything in a json object. Since you cannot put binary in a json object it converts it to a string which breaks the binary.

This worked perfect for me:

function getBase64(url) {
  return axios
    .get(url, {
      responseType: 'arraybuffer'
    })
    .then(response => new Buffer(response.data, 'binary').toString('base64'))
}

if you are on node like me and you are using v >= 6, there was a change and you should use Buffer.from or similar.

function getBase64(url) {
  return axios
    .get(url, {
      responseType: 'arraybuffer'
    })
    .then(response => Buffer.from(response.data, 'binary').toString('base64'))
}

Reference safe-buffer
new Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead

@sean-hill Do you have any idea why it can't get the first token of the image? I don't see data:image/png;base64, part for some reason, which makes the base64 data invalid

this work for me

function getImage(imageUrl) {
var options = {
    url: `${imageUrl}`,
    encoding: "binary"
};
  return new Promise(function (resolve, reject) {
    request.get(options, function (err, resp, body) {
        if (err) {
            reject(err);
        } else {
            var prefix = "data:" + resp.headers["content-type"] + ";base64,";
            var img = new Buffer(body.toString(), "binary").toString("base64");
            //  var img = new Buffer.from(body.toString(), "binary").toString("base64");
            var dataUri = prefix + img;
            resolve(dataUri);
        }
    })
})
}
function getImage(imageUrl) {
var options = {
    url: `${imageUrl}`,
    encoding: "binary"
};

    request.get(options, function (err, resp, body) {
        if (err) {
            reject(err);
        } else {
            var prefix = "data:" + resp.headers["content-type"] + ";base64,";
            var img = new Buffer(body.toString(), "binary").toString("base64");
           //  var img = new Buffer.from(body.toString(), "binary").toString("base64");
            var dataUri = prefix + img;
        }
    })
}
return axios.get('http://site.com/img.png', { responseType: 'arraybuffer' })
  .then(response => `data:${response.headers['content-type']};base64,${btoa(String.fromCharCode(...new Uint8Array(response.data)))}`);
return axios.get('http://site.com/img.png', { responseType: 'arraybuffer' })
  .then(response => `data:${response.headers['content-type']};base64,${btoa(String.fromCharCode(...new Uint8Array(response.data)))}`);

Node Version:

    return axios.get(url, { responseType: 'arraybuffer' }).then(res => {
      ;`data:${res.headers['content-type']};base64,${Buffer.from(String.fromCharCode(...new Uint8Array(res.data)), 'binary')
        .toString('base64')}`
    })

@voidpls
your method cause error!
Uncaught RangeError: Maximum call stack size exceeded

it cause from
toa(String.fromCharCode(...new Uint8Array(response.data)))

you can try this picture
texture 4a95078a

Was this page helpful?
0 / 5 - 0 ratings