Axios: 如何将图像从获取请求转换为 base64

创建于 2016-11-01  ·  10评论  ·  资料来源: axios/axios

npm 中的任何库都可以做到这一点?

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

最有用的评论

如果您像我一样在节点上并且使用v >= 6 ,则发生了变化,您应该使用Buffer.from或类似的。

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

参考安全缓冲区
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

所有10条评论

我认为这是 StackOverflow 的问题。

对于任何寻找解决方案的人,我有以下代码:

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
}

这是我们的解决方案,它就像一个魅力

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

这行不通的原因是 axios 将所有内容都放在 json 对象中。 由于您不能将二进制文件放入 json 对象中,因此它会将其转换为破坏二进制文件的字符串。

这对我来说很完美:

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

如果您像我一样在节点上并且使用v >= 6 ,则发生了变化,您应该使用Buffer.from或类似的。

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

参考安全缓冲区
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 你知道为什么它不能得到图像的第一个标记吗? 由于某种原因,我没有看到data:image/png;base64,部分,这使得 base64 数据无效

这对我有用

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

节点版本:

    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
你的方法导致错误!
Uncaught RangeError: Maximum call stack size exceeded

它导致从
toa(String.fromCharCode(...new Uint8Array(response.data)))

你可以试试这张图片
texture 4a95078a

此页面是否有帮助?
0 / 5 - 0 等级