Axios: 画像をgetリクエストから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 評価